VB.net and Powershell command

Brock Eldridge 21 Reputation points
2022-01-18T22:15:11.12+00:00

Hello,

I'm having difficulty running a Powershell command from within VB.net, I'm trying to get a Bitlocker key that is stored in our AD, The code I have works in powershell but when I try it in .Net it fails to pass to the result variable.

my code:

  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())

The error message I'm getting is "'Index was out of range. Must be non-negative and less than the size of the collection. " on this line MsgBox(results.Item(0).ToString())

Developer technologies VB
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2022-01-19T03:14:02.433+00:00

    Hi @Brock Eldridge ,
    Probably the return value is empty.
    You can try the code below and see its result.

            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  
    

    Hope this could be helpful.
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.