Calling PowerShell Script from VB.net. Script can't find WinSCPnet.dll when it's in System32 directory Windows 10 VS2019 - vb.net

VB.NET Process Code I am using to invoke
Dim p As Process = New Process()
p.StartInfo.FileName = "PowerShell.exe"
p.StartInfo.Arguments = "C:\Users\dbashore\Documents\SFTP2.ps1"
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
p.StartInfo.UseShellExecute = False
p.StartInfo.CreateNoWindow = True
p.StartInfo.RedirectStandardError = True
p.Start()
p.WaitForExit()
Dim sStdErr_psRename As String = p.StandardError.ReadToEnd()
Console.WriteLine("Exit code : {0}", p.ExitCode)
Console.WriteLine("StdErr : {0}", sStdErr_psRename)
Here is the PowerShell Line that is failing
Add-Type -Path "C:\Windows\System32\WinSCPnet.dll"
Error says no such file exists.
When I copy the DLL to Mydocuments and change the path to point there the script runs.
Why can't it use .DLL's directly from system32. I'm sure it related to elevated permisions but i can't find anything about what property needs to be added/changed
The script runs fine from PoweshellISE
Thanks
Dean

Related

TF.exe doesn't prompt for checkin confirmation when executed directly, without using the operating system shell to start the process

I'm using TF.exe command-line for some simple TFS commands such as getting the latest version of the files (tf.exe vc get), checking out some files (tf.exe vc checkout) and then checking them in at the end of use (tf.exe vc checkin).
After some tests I've noticed that when I run the checkin command through Windows Command Prompt (cmd.exe), the prompt window is displayed asking for confirmation before the check-in command is done:
C:\Program Files\Microsoft Visual Studio\2022\Community
\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer>
tf.exe vc checkin "C:\TfsTestProject\test.txt" /comment:"Checked via command-line."
For my project that was a good thing, displaying the prompt window for check-in confirmation.
However, when I started the TF command through code I found a problem: I have to start the TF.exe process redirecting the standard output, so I can display what's happening when the command is executed, and for that I have to set process.StartInfo.UseShellExecute = False. But when I do that, the prompt window is no longer displayed, as if I was using the /noprompt parameter (and I'm not using it).
So, when I use the code below the prompt window is stil displayed, as in the picture, but I cannot receive the standard output stream feedback:
Dim p = New Process()
' I removed the full path for clarity, but that's:
' "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe"
p.StartInfo.FileName = "TF.exe"
p.StartInfo.Arguments = $"vc checkin ""{testFilePath}"" /comment:""Checked via code."""
p.StartInfo.UseShellExecute = True
p.StartInfo.CreateNoWindow = True
p.Start()
p.WaitForExit()
But, when I use this other code, the one that I need, the prompt window for check-in confirmation is no longer displayed, even though I'm not using /noprompt parameter:
Dim p = New Process()
' I removed the full path for clarity, but that's:
' "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe"
p.StartInfo.FileName = "TF.exe"
p.StartInfo.Arguments = $"vc checkin ""{testFilePath}"" /comment:""Checked via code."""
p.StartInfo.UseShellExecute = False ' <- That's the problem, apparently.
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.CreateNoWindow = True
p.EnableRaisingEvents = True
AddHandler p.OutputDataReceived, Sub(s, e) Console.WriteLine(e.Data)
p.Start()
p.BeginOutputReadLine()
p.WaitForExit()
I couldn't find any information about that behaviour, maybe it's just a bug?
Shame on me, I've done some research before posting the question and found nothing, but, just after posting it I found this:
c# - How can I capture tf.exe stderr without stopping its dialog prompts? - Stack Overflow
This problem is old, since that question is from 10 years ago, facing the same "bug". Apparently there is an undocumented parameter /prompt that makes the prompt window to be displayed even though the TF command is not executed through shell.
So this code (with undocumented /prompt parameter) worked:
Dim p = New Process()
' I removed the full path for clarity, but that's:
' "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe"
p.StartInfo.FileName = "TF.exe"
' With undocumented /prompt parameter the prompt window is
' displayed even when the command is not executed through shell.
p.StartInfo.Arguments = $"vc checkin ""{testFilePath}"" /prompt /comment:""Checked via code."""
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.CreateNoWindow = True
p.EnableRaisingEvents = True
AddHandler p.OutputDataReceived, Sub(s, e) Console.WriteLine(e.Data)
p.Start()
p.BeginOutputReadLine()
p.WaitForExit()
And after that question and answer from long time ago I've tested a little more and found that I was wrong, the problem is not about not starting the command from shell, the problem really happens when the streams (output or error) are redirected. When you just set UseShellExecute = False, without redirecting, the prompt window is still displayed.

git is not recognized when running a batch job in Visual Basic application

I have a VB app that I want to pull down a repo upon a button click.
Upon button click, my project runs a .cmd file (Frontend.cmd) that I have saved in my project resources folder:
cd ..
cd ..
cd Users\Username\Documents
git clone https://gitusername:token#github.com/repofilepath.git
PAUSE
Running Frontend.cmd normally works without issue, the repo is pulled down successfully. However, when running the .cmd file through the VB application, I get the git is not recognized error.
'git' is not recognized as an internal or external command,
operable program or batch file.
I have added C:\Program Files\Git\bin\ and C:\Program Files\Git\cmd\ paths as suggested in this answer:
'git' is not recognized as an internal or external command
Is there another path I must add?
Here is my button click code if needed:
Dim output As String
output = My.Resources.Frontend
Dim programPath As String = Path.GetTempPath & “\” & program & ".cmd"
Using sw As StreamWriter = New StreamWriter(programPath)
sw.Write(output)
End Using
If (My.Computer.FileSystem.FileExists(programPath)) Then
Dim procStartInfo As New ProcessStartInfo
Dim procExecuting As New Process
With procStartInfo
.UseShellExecute = True
.FileName = programPath
.WindowStyle = ProcessWindowStyle.Normal 'use .hide to hide the process window
.Verb = "runas" 'run as admin
End With
MsgBox("Please press Yes when system ask permissions", MsgBoxStyle.Information, "myProgram")
procExecuting = Process.Start(procStartInfo)
End If

Invoking the .bat file by passing arguement from vb.net application

From Vb.Net Application, i am calling .bat file by passing SourceFile , DestinationFile. The .Bat file transfers source file to the destination folder. If i call .bat file directly from command prompt by passing arguements, file is getting transfered.
My code fails to transfer the file. I am not able to find the error where the code fails to execute the .bat file.
Dim strBatchFile As String = String.Empty
strBatchFile = AppDomain.CurrentDomain.BaseDirectory
strBatchFile = strBatchFile.Replace("\bin\Debug", "\ShellScript")
strBatchFile = strBatchFile & "callsfxcl.bat"
Dim proc As New System.Diagnostics.Process()
proc.StartInfo.UseShellExecute = False
proc.StartInfo.FileName = strBatchFile
proc.StartInfo.Arguments = String.Format("{0},{1}", strSourceFile, sSFTP)
proc.StartInfo.CreateNoWindow = True
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
proc.Start()
Batch files are run by cmd.exe. cmd /c batfile.bat. If you had of set UseShellExecute to true Windows would have done it for you. I suspect you didn't read the error.
From .NET help fror filename property.
The set of file types available to you depends in part on the value of the UseShellExecute property. If UseShellExecute is true, you are able to start any document and perform operations on the file, such as printing, with the Process component. When UseShellExecute is false, you are able to start only executables with the Process component.
Batch files are run by cmd.exe.
cmd /c batfile.bat.
So cmd is your process and /c c:\path\batch.bat is your arguments.

Run already opened process in vb.net

I have a windows form that, on the click of a button, runs a process (MATLAB) and executes a file.
Dim myProcesses() As Process
myProcesses = Process.GetProcessesByName("Matlab")
If myProcesses.Count > 0 Then
'~~~~ what goes here? ~~~~
Else
Dim startInfo As New ProcessStartInfo
startInfo.FileName = "C:\Program Files\MATLAB\R2011b\bin\matlab.exe"
startInfo.WorkingDirectory = MatlabDir 'MatlabDir is defined elsewhere
startInfo.Arguments = "matlab.exe -r test_plot2"
Process.Start(startInfo)
End If
The above code opens MATLAB and executes the script "test_plot2.m" if MATLAB isn't already open. But what do I write in the first IF statement, if MATLAB is already open, and all I want to do is run the file?
Thanks in advance.
Its supposed to be the same. I mean, it doesn't matter if its opened or not, unless the application (Matlab) manages something different, then you have to guess how. Have you tried just using the same code?
Example:
Dim startInfo As New ProcessStartInfo
startInfo.FileName = "notepad.exe"
startInfo.Arguments = "C:\temp\test.txt"
Process.Start(startInfo)
It doesn't matter if you have Notepad already opened or not.

Run batch file in vb.net?

How can I run a batch from from within vb.net?
You can use the Process class to run a batch file
Dim psi As New ProcessStartInfo("Path TO Batch File")
psi.RedirectStandardError = True
psi.RedirectStandardOutput = True
psi.CreateNoWindow = False
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.UseShellExecute = False
Dim process As Process = Process.Start(psi)
Here is a simple and straight forward method:
System.Diagnostics.Process.Start("c:\batch.bat")
The best way is to use the Process.Start and pass the path to the batch file
Process.Start(pathToBatchFile)
The easiest way if you know the exact location of the file is
System.Diagnostics.Process.Start("c:\test\file.bat")
In Visual Studio the file must exist in the /bin/debug or /bin/release depending on your current build configuration
System.Diagnostics.Process.Start("test.bat")