我正在尝试从我的表单运行 PowerShell 脚本。我在我的项目中添加了一个名为“System Management Automation”的 NuGet 包,它可以从 vb.net 程序与 PowerShell 进行交互。并在包文件夹中添加了对 System.Management.Automation.dll 的项目引用。下面是我用来尝试运行 PowerShell 脚本的代码。
Imports System.Collections.ObjectModel
Imports System.Diagnostics
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.Text
Public Class FormMain
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBoxConsole.AppendText(RunScript("cls"))
End Sub
Private Function RunScript(ByVal script As String) As String
Dim runspace As Runspace = RunspaceFactory.CreateRunspace
runspace.Open()
Dim pipeline As Pipeline = runspace.CreatePipeline
pipeline.Commands.Add("cls")
pipeline.Commands.AddScript(script)
pipeline.Commands.Add("Out-String")
Dim results As Collection(Of PSObject) = pipeline.Invoke
runspace.Close()
Dim stringBuilder As StringBuilder = New StringBuilder()
For Each ps As PSObject In results
stringBuilder.AppendLine(ps.ToString)
Next
Return stringBuilder.ToString()
End Function
End Class
但是,当我单击时,Button1
出现以下异常:
System.Management.Automation.dll 中出现“System.Management.Automation.SetValueInvocationException”类型的未处理异常
附加信息:异常设置“CursorPosition”:“提示用户的命令失败,因为主机程序或命令类型不支持用户交互。尝试支持用户交互的主机程序,例如Windows PowerShell Console或Windows PowerShell ISE ,并从不支持用户交互的命令类型(例如 Windows PowerShell 工作流)中删除与提示相关的命令。”