在Powershell脚本中测试PC是否可以通过网络访问并运行任务如果可以

问题描述

我有一个网络中的计算机列表,想知道一台计算机是否可以通过网络访问。我想在每台计算机上运行命令,但是如果无法访问计算机,则会出现错误,我想知道是否可以在脚本上的每台PC上运行ping命令,并且如果PC在网络中则捕获true或false。 / p>

代码

-Get  file name  by opening a Windows  file  search menu.
-Get  file with all  hosts to run command  on 
-Iterate over hosts 
    -run if   statement   ( if  PC   pingable  )
        -run main action command  
    -if PC not pingable  
skip  and repeat ..

有没有办法可以从ping捕获真假?

到目前为止,如果列表中的每台PC都可以访问,则代码可以正常工作

Start-Transcript -Path "$(Get-location)\Client-log-$(Get-date -Format "yyyyMMddTHHmmss").log"

Function Get-FileName{
  
 [System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) |
 Out-Null

 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
 $OpenFileDialog.initialDirectory = Get-Location
 $OpenFileDialog.filter = “All files (*.*)| *.*”
 $OpenFileDialog.ShowDialog() | Out-Null
 $OpenFileDialog.filename
}

$Importfile = Get-FileName

$Clients = Get-Content $Importfile
Foreach($Client in $Clients){

    #inser conditional  to check if   ping is  good or bad 

    (Get-HotFix -ComputerName $Clients | sort-object -Property InstalledOn)[-1]

    }

Stop-Transcript

此脚本的基本思想是获取PC上安装的最新KB更新

解决方法

您正在寻找的是Test-Connection cmdlet。

您可以设置一个变量并测试这是对还是错。例如:

    if $testConnection 'do something'

编辑:如果您使用Quiet参数,它将在System.Boolean对象中为每个测试的连接返回一个布尔值。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...