0

我正在更新一个使用System.Management.Automation.dllv10.0.10586的旧应用程序,NuGet例如PowerShell 3.0

我的新应用是.NET 5并且我已经从 NuGet 添加了 System.Management.Automation 和 Microsoft.PowerShell.SDK 的 v7.1.0

但是运行基本代码来测试在旧版本上运行良好的代码不适用于新版本,我很困惑

例如,下面的代码片段给出了一个错误

Dim ps As PowerShell = PowerShell.Create()
ps.AddCommand("test-netconnection")
Dim result = ps.Invoke()
MsgBox(result(0).Properties("PingSucceeded").Value.ToString)
ps.Dispose()

错误:

“System.Management.Automation.CommandNotFoundException:在模块‘NetTCPIP’中找到‘test-netconnection’命令,但无法加载模块。”

请有人可以告诉为什么以前有效的方法现在不起作用?

我已经从标准PowerShell 7控制台尝试过并且test-netconnection工作正常

4

1 回答 1

0

问题解决了,与运行错误的命令无关!

尽管它在 PowerShell 控制台中运行良好,但在 VB 中运行它时却失败了,因为我需要首先运行Set-ExecutionPolicy -ExecutionPolicy UnrestrictedSet-ExecutionPolicy -ExecutionPolicy RemoteSigned

Visual Studio 调试器崩溃并显示错误,但它显示的主要错误例如

“System.Management.Automation.CommandNotFoundException:在模块‘NetTCPIP’中找到‘test-netconnection’命令,但无法加载模块。”

不是很有帮助,但是在进一步检查中提到了执行策略的内部异常之一,因此在将以下内容添加到我的代码后,它现在可以正常工作了

powershell.AddCommand("Set-ExecutionPolicy").AddParameter("Scope", "Process").AddParameter("ExecutionPolicy", "Unrestricted").AddParameter("Confirm", False).AddParameter("Force", True).Invoke()
于 2021-01-15T21:41:32.290 回答