首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在VB.NET中运行powershell -如何访问变量的内容

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

Stack Overflow用户
提问于 2021-02-01 20:44:47
回答 1查看 71关注 0票数 0

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

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

代码语言:javascript
复制
 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

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-01 21:39:17

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

可能是这样的:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65992947

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档