Running powershell scripts from within a .NET windows app - vb.net

I'm needing to run scripts from within a vb.net windows app.
I've got the scripts running in the background fine;
Using MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
MyRunSpace.Open()
Using MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
MyPipeline.Commands.AddScript("import-module -name " & moduleName &
vbCrLf &
"(get-module -name " & moduleName & ").version")
Dim results = MyPipeline.Invoke()
'Do something with the results
End Using
MyRunSpace.Close()
End Using
However, i now need to be able to have the powershell run (not in the background) eg. When prompts occur;
Set-ExecutionPolicy unrestricted
I'm currently looking into the Microsoft.PowerShell.ConsoleHost namespace to see if i can use something like;
Dim config = RunspaceConfiguration.Create
ConsoleShell.Start(config, "Windows PowerShell", "", New String() {""})
Can anyone advise me please???
EDIT: I've fudged it a bit with this;
Public Function RunPowershellViaShell(ByVal scriptText As String) As Integer
Dim execProcess As New System.Diagnostics.Process
Dim psScriptTextArg = "-NoExit -Command ""& get-module -list"""
'Dim psScriptTextArg = "-NoExit -Command ""& set-executionPolicy unrestricted"""
'Dim psScriptTextArg = ""-NoExit -Command """ & scriptText & """"
execProcess.StartInfo.WorkingDirectory = Environment.SystemDirectory & "\WindowsPowershell\v1.0\"
execProcess.StartInfo.FileName = "powershell.exe"
execProcess.StartInfo.Arguments = psScriptTextArg
execProcess.StartInfo.UseShellExecute = True
Return execProcess.Start
End Function
But there's gotta be a better way??

There is a distinction between the PowerShell engine and its host. What you're wanting is to run the engine within your application but then fire up a separate host (which also is hosting the PowerShell engine) to handle prompts. You might want to look into modifying your application to act as a host itself. You could then react to prompts (read-host) and pop dialog boxes or whatever. Take a look at this relevant PowerShell namespace. Also check out this blog post on creating a simple PSHost.

Related

Install driver inf from Visual Studio Setup project

So.. We have a C# utility application for a usb/serial device. I would like to install the driver during the setup process. I know there are lots of posts about this, and I've gone through many msdn and stackoverflow articles, but I just do not seem to succeed.
The driver is OK, it is a stock Arduino driver, so it is signed and can be installed from windows gui (right click on the inf, install)
I created a visual studio setup project for our applcation, and a VB project for the custom setup actions. The setup copies the driver to the installation folder. The driver installation is performed from the "OnCommitted" method. Here I spawn a process by calling cmd.exe and would like to call some command to install the driver.
First I tried "RUNDLL32.EXE SETUPAPI.DLL,InstallHinfSection DefaultInstall 132 ", but it is always fails, although I acquire admin rights for this.
I tried to acquire admin rights at different places:
- I tried to add a "Launch Condition" with the condition "AdminUser"
- I tried to run cmd as admin from VB (Process.Startinfo.Verb = "runas")
none of the above solved my problem.
Then I tried alternative ways to install the driver and InfDefaultInstall.exe is almost fine, but sometimes it fails on some machines, and I don't know why. pnputil.exe always fails for me.
I guess the official way to do this is calling InstallHinfSection as MSDN suggests, and I would prefer to use that. We have to support Windows 7 and above.
Any thoughts on what I do wrong?
Thanks in advance!
here are my VB methods:
Private Sub InstallDriverPNPUtil()
Dim infPath As String = """" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\arduino.inf" + """"
Dim processInfo As New ProcessStartInfo("CMD", "/C pnputil -i -a " + infPath)
processInfo.WindowStyle = ProcessWindowStyle.Hidden
Dim p As System.Diagnostics.Process = Process.Start(processInfo)
p.WaitForExit()
End Sub
Private Sub InstallDriverInfDefaultInstall()
Dim infPath As String = """" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\arduino.inf" + """"
Dim processInfo As New ProcessStartInfo("CMD", "/C InfDefaultInstall.exe " + infPath)
processInfo.WindowStyle = ProcessWindowStyle.Hidden
Dim p As System.Diagnostics.Process = Process.Start(processInfo)
p.WaitForExit()
End Sub
Private Sub InstallDriverInstallHinfSection()
Dim infPath As String = """" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\arduino.inf" + """"
Dim process As New Process()
process.StartInfo.FileName = "cmd.exe"
'fails with and without this
process.StartInfo.UseShellExecute = True
process.StartInfo.Verb = "runas"
process.StartInfo.Arguments = "/C RUNDLL32.EXE SETUPAPI.DLL,InstallHinfSection DefaultInstall 132 " + infPath
'MsgBox(process.StartInfo.Arguments, MsgBoxStyle.OkOnly, "InstallHinfSection")
process.Start()
process.WaitForExit()
End Sub

IIS Command-lets

I am trying to add a IIS website via command-lets. What I currently have:
' User input
Dim domainname As String = "niels_test"
' System vars
Dim basePath As String = "C:\Projecten\Websites\"
Dim finalDirname As String = basePath & domainname
Dim shell As PowerShell = PowerShell.Create
'shell.Commands.AddScript("mkdir """ & finalDirname & """")
shell.Commands.AddScript("New-Website -name """ & domainname & """ -PhysicalPath '" & finalDirname & "' -port 80")
Dim results = shell.Invoke()
If results.Count > 0 Then
Dim b As New StringBuilder
For Each PSObject In results
b.AppendLine(PSObject.BaseObject.ToString)
Next
Else
Throw New Exception("NORESULT")
End If
If I comment out hte line for mkdir it works. But I cannot create a new website in IIS this way. If I execute that command via the powershell on the server itself. It does work.
This code is inside a .aspx.vb file.
Any idea on how to get this working?
Sounds like a permissions issue, the user under which you are running the website/appPool does not have the rights for "C:\Projecten\Websites\".
You can fix that by assigning a user with correct privileges to the Application Pool:
iis manager -> application pools -> yourPool -> advanced settings -> Process Model -> Identity
or give your app pool rights to the folder:
folder's security tab -> edit/add -> (in locations select your server) -> IIS AppPool\yourPool

Running CMD command on windows service

I have created a windows service that requires executing an EXE file with the CMD process. I have used the following code:
Str = "C:\PCounter\Staff\account.exe CHARGE " & Name & " " & Amount & " TO" & Id
Dim procStartInfo As New System.Diagnostics.ProcessStartInfo(Str)
procStartInfo.RedirectStandardOutput = True
procStartInfo.UseShellExecute = False
procStartInfo.CreateNoWindow = True
Dim proc As New System.Diagnostics.Process
proc.StartInfo = procStartInfo
proc.Start()
proc.Dispose()
However the above code will return
system cannot find the file specified
I have tried same code on the Windows form, and its works fine. To make sure the path is correct I have added a text file in the same location as EXE file, and load the content of the text file in the service. It works fine.
I can't think of anything else; I really would appreciate it if you can help me on this.
ProcessStartInfo has two properties. One for the executable to run, and the other for the arguments to pass to the executable. The symantics for the Arguments property are the exact same as the command line.
You can not include the arguments in the same property as the executable. They must be separated.
Create service:
sc create Vm-Symantec04 binPath= "\"C:\App32\VMware\VMware Workstation\vmrun.exe\" -T ws start \"D:\VM\Sym04\Sym04.vmx\" nogui" depend= "VMAuthdService/VMnetDHCP/VMUSBArbService/VMware NAT Service" start= auto
Delete service:
sc delete Vm-Symantec04

downloading file using SFTP with VBA

My objective is to download, not upload a file from an SFTP server, and I am trying to adapt the code from another question on this site to do so (I pasted the code below for your convenience).
I downloaded PSFTP from Putty. PSFTP closes when I try to connect using the following command line:
open username:password#server.com.port:1111
I have three questions:
Is something wrong with my command line? If not then what could be the problem?
As far as I know SFTP would normally utilize get/put commands, but i don't see a put command in the code below, so I don't understand where I should enter the get command to download the file instead of uploading it (which is what the code below is supposed to be doing).
Is it correct that pRemotePath is the location of the file on the SFTP server, and pFile is the location I want the file downloaded to?
A simple explanation would be very much appreciated.
Public Sub SftpGet()
Const cstrSftp As String = """C:\Users\Ron\UtilityTools\psftp.exe"""
Dim strCommand As String
Dim pUser As String
Dim pPass As String
Dim pHost As String
Dim pFile As String
Dim pRemotePath As String
pUser = "uid"
pPass = "PW"
pHost = "dns"
pFile = "C:\Users\Ron\activity.txt"
pRemotePath = "Z:/activity.log"
strCommand = cstrSftp & " -sftp -l " & pUser & " -pw " & pPass & _
" " & pFile & " " & pHost & ":" & pRemotePath
Debug.Print strCommand
Shell strCommand, 1 ' vbNormalFocus '
End Sub
I think you should start with a Windows command prompt session. Work out the details of your command line there, as I suggested in an answer to a similar question: SFTP upload with VBA. Once you have a command line which works there, it will be very easy to execute that same command from VBA.
I've never used Putty's psftp.exe tool, only pscp.exe, so I can't offer help about how to construct your psftp.exe command line. One thing I noticed in Putty's documentation is that PSFTP (pscp.exe) can only work with a SSH-2 server --- if your target server supports only SSH-1, PSFTP will not work.
I think it would be worthwhile for you to review the Putty documentation at that link.

Running a advanced java call from VB.net

I need to run a small piece of Java code (Java is the only option in this case)
I have the jar file in the VB.net resources as JSSMCL(the extension is not required to run it, of this I am sure :P) I know I use Path.GetFullPath(My.Resources.ResourceManager.BaseName)
but no mater how I do it it fails, I have tried so many ways i have lost count!
this is the command that I need to run:
java -cp "JSSMCL.jar" net.minecraft.MinecraftLauncher username false
You can use System.Diagnostics.Process class and its method to start/run the external process.
Refer to the following code part to run the Command using Process
Sub Main()
' One file parameter to the executable
Dim sourceName As String = "ExampleText.txt"
' The second file parameter to the executable
Dim targetName As String = "Example.gz"
' New ProcessStartInfo created
Dim p As New ProcessStartInfo
' Specify the location of the binary
p.FileName = "C:\7za.exe"
' Use these arguments for the process
p.Arguments = "a -tgzip """ & targetName & """ """ & sourceName & """ -mx=9"
' Use a hidden window
p.WindowStyle = ProcessWindowStyle.Hidden
' Start the process
Process.Start(p)
End Sub
EDIT:
Use the Coding part like below, may be it works
-jar "compiler.jar" --js_output_file="myOutput.min.js" --js="input1.js" --js="input2.js"
Have a look at this link for your problem