vb.net - System.Management.Automation.SetValueInvocationException
问题描述
我正在尝试从我的表单运行 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 工作流)中删除与提示相关的命令。”
解决方案
Clear-Host
(别名cls
)通过调用宿主应用程序的宿主用户界面来工作 - 如果您不提供 UI 实现,它将没有任何可操作的东西,这就是您看到抛出异常的原因。
要么实现主机 UI,要么避免调用依赖可用的函数
推荐阅读
- python - SQLALCHAM 关系
- java - 使用 JPA 的 varchar 中的内容长度
- aggregation-framework - 在 $slice 中使用表达式
- kotlin - (保存设置失败,请重启IntelliJ IDEA)下载intellij idea 2020.2并导入2020.1制作的项目后报错
- c# - SMTP 需要安全连接网络邮件
- swift - 如何获取管理 API 访问令牌以在 Auth0 /api/v2/users 端点上使用
- replace - Notepad++ - 增量替换所有数组索引
- c# - 如何 JSON 反序列化子对象 ASP.NET Core
- xslt - xslt 转换为 html 使用 select="format-date(@ДатаРожд, '[D01].[M01].[Y0001]')" 结果:[语言:en]19.09.2014
- node.js - webpack 没有将入口点代码拆分为单独的输出文件