ProcessStartInfo giving Error: The system cannot find the file specified - vb.net

I want to run a command line which provision a computer but keep getting error The system cannot find the file specified. But when I run the code through cmd it works.
Below is the code
Public Sub DjoinExe()
Dim myProcessProperties As New ProcessStartInfo
Dim strArguments As New StringBuilder
myProcessProperties.FileName = "C:\Windows\System32\djoin.exe"
If strArguments.Length <> 0 Then
myProcessProperties.Arguments = " /provision /domain blablabla.com /machine machineName /reuse /savefile C:\Apps\offlinedomainjoin.txt "
End If
Dim myProcess As Process = Process.Start(myProcessProperties)
End Sub
Thanks in advance

Related

VB.NET Communicating with console app and sending parameters

I'm creating myself a GUI for a program that can be used in CMD, a CLI.
The program has the following input:
Ex: extractor.exe filename.rar newfilename.zip -c <password for achive>
filename.rar = the original file
newfilename.zip = the file to be created with new format
-c a command meaning key
<password...> - here comes the archive password.
It's great on CMD, but I would like to make a GUI.
I do it in VB and so:
For filename.rar I have one textbox that goes filled with a path specified by user using OpenFileDialog1.
For newfilename.zip I use a savefiledialog and a textbox: The textbox gets the path specified by user
Another textbox3 for the password and a button to call extractor.exe:
How can I pass these arguments to extractor?
I have tried with
argument = textbox1.text + textbox2.text + "-c" + textbox3.text
The program starts but simply closes as it simply doesn't get the parameters.
I have also tried this:
Dim psi As ProcessStartInfo
Dim procname = "extractor.exe"
Dim filename = TextBox1.Text
Dim newfile = TextBox3.Text
Dim key = TextBox2.Text
Dim args = ("extract" + filename + newfile + "-k" + key)
psi = New ProcessStartInfo(procname, args)
Dim proc As New Process()
proc.StartInfo = psi
proc.Start()
No luck. I'm able to send 1 parameter if I do like
argument = "extract" but i have multiple arguments that needs to be fetched from textboxes....is there a way?
Thanks!

Need help getting Registry.GetValue to work correctly

I have a simple setup project that is no longer working and it seems like a windows update is the cause. I am using Visual Studio 2010 on Windows 7. The project is 64bit. It still works on some computers but it does not work on any computers that have had updates recently.
Here is the original code:
Dim appPath As String = Registry.GetValue("HKEY_CURRENT_USER\SOFTWARE\Our Company Inc.\SoftwareName.exe", "Path", "Not Found")
appPath &= "Colorbar.col"
Dim sid : sid = "S-1-1-0"
Dim objWMI : objWMI = GetObject("winmgmts://./root\cimv2")
Dim objSID : objSID = objWMI.Get("Win32_SID='" & sid & "'")
Dim userAccount As String = objSID.AccountName
Dim fileInfo As IO.FileInfo = New IO.FileInfo(appPath)
Dim fileAcl As New FileSecurity
fileAcl.AddAccessRule(New FileSystemAccessRule(userAccount, FileSystemRights.FullControl, AccessControlType.Allow))
fileInfo.SetAccessControl(fileAcl)
I have put the key value pair of "Path" and "[TARGETDIR]" in the registry editor and have the output from this installer class (the code above) in the Install and Commit custom actions.
This code that used to work now returns "Exception has been thrown by the target of an invocation -> C:\Windows\SYSWOW64\Colorbar.col"
I have checked the registry when this message appears and the path is correct so I don't know where SYSWOW64 is coming from.
I have tried to change getting the appPath using this code:
Dim regKey As RegistryKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)
regKey = regKey.OpenSubKey("SOFTWARE\Our Company Inc.\SoftwareName.exe")
Dim appPath As String = regKey.GetValue("Path").ToString
This returns an "Object reference not set to an instance of an object" error.
I have made a test Windows Form application and put both versions of code in a button event. Everything works as expected. Any ideas why the code does not work in a setup project anymore and what I can do to get it working again?
Thanks in advance.
Finally have it working again. I got around using the registry by using the custom action's CustomActionData and setting it to:
/name="[TARGETDIR]\"
I was then able to access it in my installer class by using this line of code:
Dim appPath As String = Context.Parameters.Item("name")
Once the path was set, everything else worked as expected. The final code looks like this:
Public Overrides Sub Commit(ByVal stateSaver As System.Collections.IDictionary)
MyBase.Commit(stateSaver)
Dim appPath As String = Context.Parameters.Item("name")
appPath = appPath.Remove(appPath.Length - 1)
appPath &= "Colorbar.col"
Dim sid : sid = "S-1-1-0"
Dim objWMI : objWMI = GetObject("winmgmts://./root\cimv2")
Dim objSID : objSID = objWMI.Get("Win32_SID='" & sid & "'")
Dim userAccount As String = objSID.AccountName
Dim fileInfo As IO.FileInfo = New IO.FileInfo(appPath)
Dim fileAcl As New FileSecurity
fileAcl.AddAccessRule(New FileSystemAccessRule(userAccount, FileSystemRights.FullControl, AccessControlType.Allow))
fileInfo.SetAccessControl(fileAcl)
End Sub

Getting DNS Cache in vb.net and returning domains

What's the best way to get the DNS Cache in Visual Basic and returning recently resolved domains? I only need the domains to compare them whit a list.
Function GetDnsCache()
Dim DNSCache As New Process
DNSCache.StartInfo.FileName = "ipconfig"
DNSCache.StartInfo.Arguments = "/displaydns "
DNSCache.StartInfo.UseShellExecute = False
DNSCache.StartInfo.RedirectStandardOutput = True
DNSCache.
DNSCache.Start()
MsgBox(DNSCache.StandardOutput.ReadToEnd())
DNSCache.WaitForExit()
End Function
This is not the cleanest way of doing this and it also takes ages to parse and load.
I would do something like this. It executes ipconfig /displaydns and appends the output to a file. Then, the file is read line by line and displayed wherever you want (I've used a Listbox)
Dim Shell = CreateObject("Wscript.Shell")
Shell.run("cmd /c ipconfig /displaydns >> C:\ipconfig.txt")
Using reader As New IO.StreamReader("C:\ipconfig.txt")
While Not reader.EndOfStream
Dim currentLine As String = reader.ReadLine()
ListBox1.Items.Add(currentLine)
End While
End Using
Should you like to display the info into a MsgBox...
Dim Shell = CreateObject("Wscript.Shell")
Shell.run("cmd /c ipconfig /displaydns >> C:\ipconfig.txt")
Dim reader as As New IO.StreamReader("C:\ipconfig.txt")
MsgBox(reader.ReadToEnd.ToString, MsgBoxStyle.Information)

unable to run Exchange Powershell through vb.net application

So I'm going round in circles trying to get this to work, I've been trying for two days and I just can't figure it out.
I have the following vb function that takes a created powershell script, and should run it in powershell. Everything works fine, until the point at which the command pipeline is invoked. At this point, no commands run.
As you can see, I have tried to add the Microsoft.Exchange.Management.PowerShell.E2010 snapin to the runspace, it didn't like that at all stating something along the lines of the snapin didnt exist (which it does), and also when I run the code as shown, no commands are recognised as valid. I even added the specific command "Add-PSSnapin" to try and load any Exchange snapins, but it states that "Add-PSSnapin" is not recognised as a valid command.
If I pause the program just before the commands are involked, I can see every command within the pipeline, in the correct format. If I copy and paste the command text in the pipeline directly into a powershell window, it runs fine.
My code is below, any suggestions welcome.
edit: I have also tried adding the line "Add-PSSnapin Ex" (with an asterisk each side of Ex - I cant figure the formatting out on this, sorry)
to try and load the Exchange PS Snapins as the first thing the script would run (opposed to setting this up in the runspace) but no luck
Private Function scriptRunner(ByVal scripttorun As String) As String
Dim initial As InitialSessionState = InitialSessionState.CreateDefault()
Dim result As String = ""
Dim lineFromScript As String = ""
Dim reader As New StreamReader(tempScript)
Dim rsConfig As RunspaceConfiguration = RunspaceConfiguration.Create()
Dim snapInException As New PSSnapInException
Dim strUserName As String = "DOMAIN\USER"
Dim strPassword As String = "PASSWORD"
Dim SecuredPSWD As New System.Security.SecureString()
For Each character As Char In strPassword
SecuredPSWD.AppendChar(character)
Next
Dim wsmConnectionInfo As WSManConnectionInfo
Dim strSystemURI As String = "http://SERVER.DOMAIN/powershell?serializationLevel=Full"
Dim strShellURI As String = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"
Dim powerShellCredentials As PSCredential = New PSCredential(strUserName, SecuredPSWD)
wsmConnectionInfo = New WSManConnectionInfo(New Uri(strSystemURI), strShellURI, powerShellCredentials)
Dim runspace As Runspace = RunspaceFactory.CreateRunspace(wsmConnectionInfo)
Runspace.Open()
' runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", snapInException)
Dim pipeLine As Pipeline = runspace.CreatePipeline()
Dim command As Command = New Command("")
' TEST >> pipeLine.Commands.Add("Add-PSSnapin *Ex*")
Do While reader.Peek() <> -1
lineFromScript = Nothing
lineFromScript = reader.ReadLine()
pipeLine.Commands.Add(lineFromScript)
'command.Parameters.Add(lineFromScript)
'pipeLine.Commands.Add(command)
Loop
'' Run the contents of the pipeline
Dim psObjCollection As Collection(Of PSObject) = pipeLine.Invoke()
runspace.Close()
runspace.Dispose()
Return ""
End Function
I ended up working around the problem rather than fixing it.
I moved the script code into the vb.net application, and wrote each line to a file, i.e.
writer.WriteLine("Add-PSSnapin *Ex*")
Then I loaded the script through PowerShell as an application;
Dim exeStartInfo As System.Diagnostics.ProcessStartInfo
Dim exeStart As New System.Diagnostics.Process
exeStartInfo = New System.Diagnostics.ProcessStartInfo("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")
exeStartInfo.Arguments = ("-command work\scriptbuilder.ps1")
exeStartInfo.WorkingDirectory = "C:\ExchangeManager\"
exeStartInfo.UseShellExecute = False
exeStart.StartInfo = exeStartInfo
exeStart.Start()
exeStart.Close()
Not ideal but it got the job done.

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.