Import-Module not working from within WinForms Application - vb.net

I have a VB.net app where I invoke Import-Module on a PowerShell from within my vb.net Window Application but the error says it could not find the module. Error as below.
Import-Module : The specified module 'MSOnline' was not loaded because no valid module file was found in any module directory.
When I load the same Module by launching the PowerShell externally in the usual way it works fine. Image as below.
The VB script is as below
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim procStartInfo As New ProcessStartInfo
Dim procExecuting As New Process
With procStartInfo
.UseShellExecute = True
.FileName = "powershell.exe"
.WindowStyle = ProcessWindowStyle.Normal
.Verb = "runas" 'add this to prompt for elevation
Dim psscript As String = My.Resources.mymsolPS
procStartInfo.Arguments = psscript
procExecuting = Process.Start(procStartInfo)
End With
End Sub
My PowerShell Script is saved in my.resource as a txt file. My PowerShell Script is as below.
Import-Module Msonline
Connect-msolService
I replaced the PowerShell script to Get-Help and that works only it dosnt work when I use Import-Module Msonline.
One more information that can be shared is the module is stored in the below location.
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\MSOnline\MSOnline.psd1
Any Help is greatly appreciated.
Thanks in Advance
Update 2:
More fiddling with it found some thing which i am not sure if is relevant.
If I launch the powershell from within my VB.net and run the below command I cant see the MSOnline module.
PS C:\windows\system32>> cd $env:WINDIR\System32\WindowsPowerShell\v1.0\Modules\
PS C:\windows\System32\WindowsPowerShell\v1.0\Modules>> dir
If I run the PowerShell directly from my system and run the above script I can see the Module
d----- 11/22/2017 2:59 PM MSOnline
Still a mystery for me which I cant crack. :(

A difference I notice is when launching from your app, or locally, the directory is either your user, or system.. so maybe the way PS is being loaded it can't find the module.
What about if you provide a full path to the module?
I've had much better luck using RunSpace - I use it to pass any powershell commands - here are a snippet from one of the sites and some examples to look at:
'Create the runspace.
Using R As System.Management.Automation.Runspaces.Runspace = _
System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()
'Create the pipeline
Using P As System.Management.Automation.Runspaces.Pipeline = R.CreatePipeline()
'Open the runspace.
R.Open()
'Create each command (in this case just one)...
Dim Cmd As New System.Management.Automation.Runspaces.Command("C:\script.ps1", True)
'...and add it to the pipeline.
P.Commands.Add(Cmd)
'Execute the commands and get the response.
Dim Result As System.Collections.ObjectModel.Collection(Of _
System.Management.Automation.PSObject) = P.Invoke()
'Close the runspace.
R.Close()
'Display the result in the console window.
For Each O As System.Management.Automation.PSObject In Result
Console.WriteLine(O.ToString())
Next
End Using
End Using
http://www.winsoft.se/2009/08/execute-a-cmdlet-or-ps1-script-from-visual-basic/
https://social.msdn.microsoft.com/Forums/vstudio/en-US/5d2279c8-e02c-45eb-a631-951c56067bb5/run-powershell-script-from-vbnet?forum=vbgeneral
https://code.msdn.microsoft.com/windowsdesktop/VBPowerShell-6b4f83ea
The last one provides a pretty solid breakdown of what it's doing. Let me know if you can't get it to work, I can try to see if this import works on an app.

I actually found the solution after hours of pain. This is pretty silly solution.
Went I went to my application Properties I found that the Preferred run was set to 32 bit hence when my PowerShell was launched from within it was looking for the module under SYSWOW where its suppose to look it under System32. I unchecked the "Preferred 32 BIT" and not it imports the module from system 32.
Thought I should share this silly miss so that others should not suffer the same.

Related

vb.net external dos command hangs without returning output

I am running a dos command from my app, however the dos window just hangs without returning any output. It does work under Windows 8, but not Windows 7.
This is my code:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\Pico Technology\PicoScope6\picoscope.com"
process.StartInfo.UseShellExecute = False
process.StartInfo.Arguments = "/a Measurements.CSV?"
process.StartInfo.RedirectStandardInput = True
process.StartInfo.RedirectStandardOutput = True
process.Start()
Dim reader As StreamReader = process.StandardOutput
Dim output As String = reader.ReadToEnd()
RichTextBox1.Text = output
End Sub
picoscope.com is a 'wrapper' supplied by the PicoScope vendor - it appears to be a very small .net app, which calls the main PicoScope.exe program with some commands (unknown). The PicoScope.exe app needs to be running for this to work.
I wrote a small console app, and this works just fine - however I can't even call my console app from a forms based application.
Code for console app:
Sub Main()
Dim process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\Pico Technology\PicoScope6\picoscope.com"
process.StartInfo.Arguments = "/a Measurements.CSV?"
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
process.Start()
' Synchronously read the standard output of the spawned process.
Dim reader As StreamReader = process.StandardOutput
Dim output As String = reader.ReadToEnd()
process.WaitForExit()
process.Close()
End Sub
This seems to be some strange issue with Windows 7.
I can open cmd.exe without any issue, as well as spawn other applications.
It's almost as if there is some conflict between the running picoscope programs and my application.
Attempting to debug doesn't seem to help at all, with the exception of this:
A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
I have tried several different approaches, disabling shell redirection, even trying to redirect the output to a file. But it would appear that anything to do with this Picoscope app just prevents it working.
I even tried writing another console app to redirect text output to the console and to a file and they worked (because the picoscope app wasn't involved!).
Likewise, a simple dos batch file with "echo Hello World" in it is successfully redirected to my forms app - so I'm sure my code is correct.
I am now at a loss as to what the issue could be here.
I'm using Visual Studio 2013, Windows 7 on SP1.
Can anyone offer any suggestions?
Apologies for the long post, I was trying to give as much detail as possible.
EDIT: Even more curious is that I tried my working app on another Windows 7 PC and it works...
I suspect this must be related to my specific Windows 7 PC (a fresh build).
I compared UAC settings with the other PC - they are the same.
Thanks.

Access to path is denied when trying to import from the client's desktop with SSIS

I'm creating a html page that will import an excel file in to a tracking system. On a button click event excel file is located / ssis package is fired / data imported then closed out. Thats the idea work flow. Problem is the excel file access is being denied before the package even executes
Here is the exact error :
I've tried :
excel file properties have been shared to everyone
identity impersonate set to true
hard coding the path
here is the VB code
Protected Sub bntExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim app As Application = New Application()
Dim package As Package = Nothing
'Dim fileName As String = "C:\Users\Desktop\T. Bryant III\PTSID_Update_Template"'
Try
Dim fileName As String = Server.MapPath(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName.ToString()))
FileUpload1.PostedFile.SaveAs(fileName)
package = app.LoadPackage("#C:\Users\Desktop\T.Bryant III\KitImport", Nothing)
'excel connection from package'
package.Connections("SourceConnectionExcel").ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0data source =" + fileName + "Extended Properties = Excel 8.0"
'Execute the pakage'
Dim results As Microsoft.SqlServer.Dts.Runtime.DTSExecResult = package.Execute()
Catch ex As Exception
Throw ex
Finally
package.Dispose()
package = Nothing
End Try
End Sub
Thanks in advance or if there is an easier way to do this please let me know. The package when executing it in ssis works fine with its own connection manager etc.
A few things to try. If they don't work for you as permanent solutions, they should at least confirm that your code is working and you are dealing with a persmissions issue (which appears to be the case).
Move your file to the public folder (C:\Users\Public).
Run your application (or web browser) as an administrator (if applicable to your version of Windows).
If you are using a web browser, try using a different one.
If nothing else works, try pasting your code into a Windows Form Application.
If you still get the same error after trying all of this, it's time to take another look at your code. Remove the Try/Catch block to determine precisely which line is throwing the error. If you've tried hard coding, I'm guessing it's the SaveAs method. I'm not sure what class FileUpload1 is, but some SaveAs methods won't overwrite existing files unless you explicitly tell them to. Check the appropriate documentation and see if you don't need to pass a True value somewhere along with filename.
Update us with the results. At the very least, this should narrow down your problem and allow for a better diagnosis of it.

Autorun of vb.net program with command line parameters does not work

I am writing an application that needs admin rights to run in VB.NET (VS2012,framework 4)
It is an app to protect the Hosts file from modification.
I want the app to start automatically with windows with the command line argument "autorun".
So I have made a check box with the following code:
Private Sub CheckBox_autoupdate_Click(sender As Object, e As EventArgs) Handles CheckBox_autoupdate.Click
Dim oreg As RegistryKey = Registry.CurrentUser
Dim okey As RegistryKey = oreg.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
If CheckBox_autoupdate.Checked = True Then
okey.SetValue("HostProtect", Application.ExecutablePath & " /autoupdate")
Else
okey.DeleteValue("HostProtect")
End If
My.Settings.Save()
End Sub
When I open regedit, the value is present but when I restart my system the program is not executed at all!
Is it because the app needs admin priviledges? How can I make it start AND correctly pass the command line argument?
Anticipating your answers!
HKey_CurrentUser entries don't run when Windows starts. They run when the user logs in and the user's registry hive is loaded. If you want it to run when Windows starts, you'll need to use HKey_LocalMachine. Or even better, write this as a Windows Service.
Application.ExecutablePath will get the .exe link, not the path, so it should be:
Application.StartupPath & " \autoupdate.exe"

VB.net - Running a java application using Shell() and set its appdata folder. multiple commands?

Alright guys I have a copy of minecraft wich is a java program launched by Minecraft.exe.
Inside the same folder is my program (lets call it launcher.exe) wich I am programming in VB.net and a Folder called LocalAppData.
If I place a shortcut in the same folder as Minecraft.exe, clear the "start in" field and put this in the target field:
C:\Windows\System32\cmd.exe /c start cd LocalAppData&& set APPDATA=%cd%\LocalAppData&& javaw -Xms4096M -Xmx4096M -cp LocalAppData\Minecraft.exe net.minecraft.LauncherFrame
then minecraft launches with my custom memory allocation from inside the LocalAppData folder. Two command windows appear as well. One closes when minecraft does, but the other does not and needs to be closed by the user
My Question is: How do I acheive the same result in VB.net instead of with a windows shortcut and is there a way to either stop the command windows appearing or setting them both to close automatically?
My goal is to launch minecraft from a subfolder, so local filepaths would be far preferrable to global filepaths, but figuring out the location of the application at runtime and working from a subfolder would be ok as well.
I thought I would be able to use the same code inside a Shell() command to produce the same effect, but it appears not.
Ideally I want to create a program that runs minecraft with:
Custom memory allocation
Local filepaths so that it can be run portably
The appdata folder changed to the subfolder so that it can be run portably
Those command windows either gone or minimised and then close automatically when minecraft is closed by the user.
I know this is a big ask, but I'm 6 months into a programming course and I'll admit that I'm not the best programmer out there.
Once I know how to do this I can create the rest of the program that manages multiple installations in seperate subfolders and lets you choose wich one to launch, but I just need help with the actual launching of the java application itself.
Note:
I should clarify that Minecraft.exe is not something that I have made and that I don't program java. I'm just looking for a solution in VB.Net.
Thank you for reading all this and sorry for the long post.
Edit
Thank you for the help. This is what I have so far, but it produces an error "Error: Could not create the JavaVirtualMachine. Error: A fatal exception has occurred. Program will exit"
'Declare Processes
Dim appDataStartInfo As ProcessStartInfo = New ProcessStartInfo()
Dim javaStartInfo As ProcessStartInfo = New ProcessStartInfo()
Dim appPath As String = Application.StartupPath()
'Launch appdata relocation process
appDataStartInfo.FileName = "cmd.exe"
appDataStartInfo.Arguments = "/c start cd " & appPath & "&& set APPDATA=" & appPath & "\LocalAppData"
appDataStartInfo.UseShellExecute = True
Process.Start(appDataStartInfo)
'Launch Minecraft
javaStartInfo.FileName = "javaw.exe"
javaStartInfo.Arguments = "-Xms4096M -Xmx4096M -cp " & appPath & "\LocalAppData\.minecraft\bin\Minecraft.jar net.minecraft.LauncherFrame"
javaStartInfo.UseShellExecute = True
Process.Start(javaStartInfo)
Does anyone see where I've gone wrong?
The Process class (http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx )allows you to launch a process. You set it up with a ProcessStartInfo instance (http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(v=vs.80).aspx ).
I don't have the time to give you all the details, but this pseudo-code should get you started :
Dim startInfo As ProcessStartInfo = new ProcessStartInfo()
startInfo.FileName = "javaw.exe" 'That's the name of your executable
startInfo.Arguments = "your argument line"
startInfo.UseShellExecute = true 'Needed to open a command window
Process.Start(startInfo)

WMI remote process to copy file

Long story short, my application needs to copy a file to a remote target where UNC connections TO the target might not be possible. However UNC connections FROM the target and BACK to the server will always be possible. So the plan was to use WMI to start a remote command shell (cmd) and use the copy command to grab the file. But this doesn't work. The following command works fine when executed manually from the command line of the target:
copy \\192.168.100.12\c$\remotefile.txt c:\localfile.txt
But when I try this same command as part of the InputParameters("CommandLine") it does not work, and produces no error. Note that I can use WMI to connect to the target and remote execution works just fine as I can start calc.exe etc. Here is the code that doesn't work:
Dim ConnectionOptions As New System.Management.ConnectionOptions
With ConnectionOptions
.Username = "target\Administrator"
.Password = "password"
End With
Dim ManagementScope As New System.Management.ManagementScope("\\192.168.100.11\root\cimv2", ConnectionOptions)
Try
ManagementScope.Connect()
MsgBox("connected")
Dim ManagementPath As New System.Management.ManagementPath("Win32_Process")
Dim ManagementOptions As New System.Management.ObjectGetOptions
Dim ManagementClass As New System.Management.ManagementClass(ManagementScope, ManagementPath, ManagementOptions)
Dim InputParameters As System.Management.ManagementBaseObject = ManagementClass.GetMethodParameters("Create")
InputParameters("CommandLine") = "cmd /c copy \\192.168.100.12\c$\remotefile.txt c:\localfile.txt"
Dim OutputParameters As System.Management.ManagementBaseObject = ManagementClass.InvokeMethod("Create", InputParameters, Nothing)
MsgBox("done")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Any ideas why this isn't working? Or does anyone have a better way of doing what I'm trying to do?
Frank you should actually give yourself credit since the method you created is likely the first ever to get around WMI limitations of remote file copy! I did 3 weeks of searching for info/workaround and yours is the only one that works! If I had any points I would vote for your solution...
I created a fully working VBS & WMI script based on your method:
InputParameters("CommandLine") = "cmd /c echo myFTPCommands > c:\ftpscript.txt"
where you replace myFTPCommands as needed with whatever script you want to go into the file c:\ftpscript.bat (or .vbs, .ps1, or whatever you like). If you couldn't fit enough text in the one-line script, then append with the same method using >>. Now, you can use XCOPY, PSEXEC, COPY, or anything else to run the script you just created on the remote host's file system.
Here's my fully fleshed out VBScript using your method. Thanks again. :)
HTH,
Lizz
For security reasons, most methods of programatically connecting to a remote machine and telling it to copy a file to itself from another machine are blocked. One thing that finally worked for me is FTP. Using the above code I can do something like this:
InputParameters("CommandLine") = "ftp -s:c:\ftpscript.txt"
Which causes the ftp commandline utility to run on the remote machine, using c:\ftpscript.txt to get a list of commands from. Since there is no way to copy the ftp script file to the target (again, no UNC connection), I can first do:
InputParameters("CommandLine") = "cmd /c echo myFTPCommands > c:\ftpscript.txt"
And this works :)
UPDATE: Never thought to use XCOPY and it works perfectly:
InputParameters("CommandLine") = "cmd /c echo F | xcopy remotefile localfile"
UPDATE: XCOPY worked yesterday, now it doesn't. NOTHING has changed, so I am at a complete loss for explanation.