我有一个 VB.net 应用程序,我在其中调用 Import-Module
在我的 vb.net 窗口应用程序中的 PowerShell 上,但错误说它找不到模块。错误如下。
Import-Module : The specified module 'MSOnline' was not loaded because no valid module file was found in any module directory.
当我以通常的方式通过外部启动 PowerShell 来加载相同的模块时,它工作正常。如下图。
VB脚本如下
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
结束子
我的 PowerShell 脚本作为 txt 文件保存在 my.resource 中。我的 PowerShell 脚本如下。
Import-Module Msonline
Connect-msolService
我将 PowerShell 脚本替换为
Get-Help
只有当我使用 Import-Module
时它才有效在线客服。可以共享的另一项信息是该模块存储在以下位置。
C:\Windows\System32\WindowsPowerShell\v1.0\Modules\MSOnline\MSOnline.psd1
任何帮助是极大的赞赏。
提前致谢
更新 2:
更多地摆弄它发现了一些我不确定是否相关的东西。
如果我从我的 VB.net 中启动 powershell 并运行以下命令,我将看不到 MSOnline 模块。
PS C:\windows\system32>> cd $env:WINDIR\System32\WindowsPowerShell\v1.0\Modules\
PS C:\windows\System32\WindowsPowerShell\v1.0\Modules>> dir
如果我直接从我的系统运行 PowerShell 并运行上面的脚本,我可以看到模块
d----- 2017 年 11 月 22 日下午 2:59 MS在线
对我来说仍然是一个我无法破解的谜。 :(
最佳答案
我注意到的一个区别是从您的应用程序或本地启动时,目录是您的用户或系统..所以也许 PS 的加载方式找不到模块。
如果您提供模块的完整路径怎么办?
使用 RunSpace 时我的运气要好得多——我用它来传递任何 powershell 命令——下面是其中一个站点的片段和一些示例:
'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
最后一个提供了它正在做什么的非常可靠的分割。如果你不能让它工作,请告诉我,我可以尝试看看这个导入是否适用于应用程序。
关于vb.net - 导入模块在 WinForms 应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47445749/