VB.net 和 Powershell 命令

Hui Liu-MSFT 40,266 信誉分 Microsoft 供应商
2024-04-22T06:38:20.58+00:00

我在 VB.net 中运行 Powershell 命令时遇到困难,我正在尝试获取存储在我们的 AD 中的 Bitlocker 密钥,我拥有的代码可以在 powershell 中运行,但是当我在 .Net 中尝试时,它无法传递给结果变量。

我的代码:

  Dim command As New PSCommand()
        command.AddScript("$computer = Get-ADComputer WS08;Get-ADObject -Filter 'objectClass -eq ""msFVE-RecoveryInformation""' -SearchBase $computer.DistinguishedName -Properties  msFVE-RecoveryPassword | Select msFVE-RecoveryPassword")

        Dim powershell As Management.Automation.PowerShell = PowerShell.Create()
        powershell.Commands = command
        Dim results = powershell.Invoke()
        MsgBox(results.Item(0).ToString())

我收到的错误消息是*"'Index was out of range. Must be non-negative and less than the size of the collection. "* 在这一行 MsgBox(results.Item(0).ToString())

Note:此问题总结整理于: VB.net and Powershell command

VB
VB
Microsoft 开发的一种面向对象的编程语言,其在 .NET Framework 上实现。 以前称为 Visual Basic .NET。
54 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Jiale Xue - MSFT 33,686 信誉分 Microsoft 供应商
    2024-04-22T08:50:24.9166667+00:00

    可能返回值为空。 您可以尝试下面的代码并查看其结果。

            Dim powershell As PowerShell = PowerShell.Create()  
            powershell.AddScript("$computer = Get-ADComputer WS08;Get-ADObject -Filter 'objectClass -eq ""msFVE-RecoveryInformation""' -SearchBase $computer.DistinguishedName -Properties  msFVE-RecoveryPassword | Select msFVE-RecoveryPassword")  
            Dim results = powershell.Invoke()  
            MessageBox.Show(results.Count)  
            For Each result As PSObject In powershell.Invoke  
                MessageBox.Show(result.ToString())  
            Next  
    

    您可以尝试使用下面的代码将命令拆分为两行。

            Dim scriptContents = New StringBuilder()  
            scriptContents.AppendLine("$computer = Get-ADComputer WS08")  
            scriptContents.AppendLine("Get-ADObject -Filter 'objectClass -eq ""msFVE-RecoveryInformation""' -SearchBase $computer.DistinguishedName -Properties  msFVE-RecoveryPassword | Select msFVE-RecoveryPassword")  
            powershell.AddScript(scriptContents.ToString)
    

    如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。

    注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助