运行 VB.NET 中的 powershell - 如何访问我的变量的内容

Running powershell in VB.NET - how to access the content of my variable

我正在 运行使用 System.Management.Automation 在 VB 中编写一个简单的脚本,如下所示

脚本 运行 很好,但是我如何在我的代码中访问 $offline 和 $online 的内容运行?

 Dim scriptContents = New StringBuilder()

    scriptContents.AppendLine("$computers = @(""PC-1"", ""PC-2"", ""PC-3"")")

    scriptContents.AppendLine("$online = @()")
    scriptContents.AppendLine("$offline = @()")

    scriptContents.AppendLine("Foreach ($computer in $computers) {")

    scriptContents.AppendLine("If (Test-Connection -ComputerName $computer -Count 2 -Quiet -ErrorAction SilentlyContinue) {")
    scriptContents.AppendLine("$online += $computer")
    scriptContents.AppendLine("}")
    scriptContents.AppendLine("Else {")
    scriptContents.AppendLine("$offline += $computer")
    scriptContents.AppendLine("}")
    scriptContents.AppendLine("}")

     Using ps As PowerShell = PowerShell.Create()

        ps.AddScript(scriptContents.ToString)

        Dim results1 As PSDataCollection(Of PSObject) = Await Task.Run(Function() ps.InvokeAsync)

        Stop

    End Using

谢谢

我认为解决方案是不要让脚本创建两个单独的数组,而是让它 return 一个 PSObjects 数组,其中每个项目都有两个属性:Computer 和一个布尔值 Online.

也许是这样的:

Dim scriptContents = New StringBuilder()

scriptContents.AppendLine("$computers = @(""PC-1"", ""PC-2"", ""PC-2"")")
scriptContents.AppendLine("Foreach ($computer in $computers) {")

scriptContents.AppendLine("If (Test-Connection -ComputerName $computer -Count 2 -Quiet -ErrorAction SilentlyContinue) {")
scriptContents.AppendLine("    [PsCustomObject]@{Computer = $computer; Online = $true}")
scriptContents.AppendLine("}")
scriptContents.AppendLine("Else {")
scriptContents.AppendLine("    [PsCustomObject]@{Computer = $computer; Online = $false}")
scriptContents.AppendLine("}")
scriptContents.AppendLine("}")

Using ps As PowerShell = PowerShell.Create()

    ps.AddScript(scriptContents.ToString)

    Dim results1 As Collection(Of PSObject) = ps.Invoke()

End Using