简体   繁体   English

在Out-Gridview中显示测试连接的成功和失败

[英]Display test-connection successes and failures in Out-Gridview

I am trying to get a list of servers and the last time they rebooted to show in a table. 我正在尝试获取服务器列表以及它们上次重新启动以显示在表中的时间。 However, if it doesn't respond to a ping, I just need it to show in the list. 但是,如果它不响应ping,则只需将其显示在列表中即可。 I can't seem to figure out how to get it to add to the table after else . 我似乎无法弄清楚如何得到它后添加到表中else

Import-CSV $Downtime | % {
if(Test-Connection $_.server -Quiet -count 1){
    Get-WmiObject Win32_OperatingSystem -ComputerName $_.server | 
    select @{LABEL="Name"; EXPRESSION = {$_.PSComputerName}}, @{LABEL="Last Bootup"; EXPRESSION = {$_.convertToDateTime($_.LastBootupTime)}}
    }
else{@{LABEL="Name"; EXPRESSION = {$_.server}}
    }
} | Out-GridView

I can always save the else results in a text file but this would be more convenient. 我总是可以将else结果保存在文本文件中,但这会更方便。

You need to make the same object, with the same properties!, in both cases so that PowerShell will understand the association between the two. 在这两种情况下,都需要制作具有相同属性的相同对象!,这样PowerShell才能理解两者之间的关联。 The follwing example builds a custom hashtable using the if/else and outputs the object for each loop pass. 以下示例使用if / else构建自定义哈希表,并为每次循环传递输出对象。

Import-CSV $Downtime | ForEach-Object {
    $props = @{}
    $server = $_.server
    if(Test-Connection $server -Quiet -count 1){
        $wmi= Get-WmiObject Win32_OperatingSystem -ComputerName $server 
        $props.Name = $wmi.PSComputerName 
        $props."Last Bootup" = $wmi.convertToDateTime($wmi.LastBootupTime)
    }else{
        $props.Name = $server
        $props."Last Bootup" = "Could not contact"
    }
    New-Object -TypeName psobject -Property $props
} | Out-GridView

I used $server as the $_ changes context a couple of time so we wanted to be able to refer to the current row in the CSV we are processing. 我几次将$server用作$ _更改上下文,因此我们希望能够引用正在处理的CSV中的当前行。

I don't know what your PowerShell version is so I will assume 2.0 and create objects that support that. 我不知道您的PowerShell版本是什么,因此我将假设2.0并创建支持该版本的对象。

In both cases an object is created with a Name and Last Bootup property which is populated based on the success of the ping. 在这两种情况下,都会创建一个具有NameLast Bootup属性的对象,该属性将根据ping的成功进行填充。

样本输出

As an aside I had a similar question a while ago about created similar object based output. 顺便说一句,我前段时间也有一个类似的问题 ,关于创建类似的基于对象的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM