powershell 将NSLookup添加到Ping脚本

xiozqbni  于 2023-03-08  发布在  Shell
关注(0)|答案(1)|浏览(186)

我有这个ping脚本,很好地为我所需要的。我想添加到这个,但不知道如何。我希望它像一个NSLookup输出。有时我有打印机的主机名,并希望它输出的IP,如果找到一个,并将其添加到另一列。
第一个EX:

Get-Content "C:\Users\Username\Desktop\New folder\hnames.txt" | ForEach-Object { #Change User to your name and after desktop where you have IPs you want to ping
  if(Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue){
    $status = 'Alive'
  }
  else {
    $status = 'Dead'
  }

$dns = Resolve-DnsName $_ -DnsOnly -ErrorAction SilentlyContinue

  # output 1 object with two separate properties
  [pscustomobject]@{
    Status = $status
    Target = $_
    IPAddress = $dns.IPAddress -join ', '
  }
} |Export-Csv 'C:\Users\Username\Desktop\New folder\output.csv' -NoTypeInformation #change this to where you want the export to go, Change Output to what you want to save as

第二次EX:

Get-Content "C:\Users\Username\Desktop\New folder\hnames.txt" | ForEach-Object { #Change User to your name and after desktop where you have IPs you want to ping
  if(Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue){
    $status = 'Alive'
  }
  else {
    $status = 'Dead'
  }

  # output 1 object with two separate properties
  [pscustomobject]@{
    Status = $status
    Target = $_
    IPAddress = $success.Address.IPAddressToString
  }
} |Export-Csv 'C:\Users\Username\Desktop\New folder\output.csv' -NoTypeInformation #change this to where you want the export to go, Change Output to what you want to save as
k4emjkb1

k4emjkb11#

如果您正在执行主机名到IP地址的转换,则可以使用Test-Connection的输出,例如:

Get-Content ..... | ForEach-Object {
    $status = 'Dead'
    if($success = Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue) {
        $status = 'Alive'
    }

    [pscustomobject]@{
        Status    = $status
        Target    = $_
        IPAddress = $success.Address.IPAddressToString
    }
} | Export-Csv ..... -NoTypeInformation

另一个选项是使用Resolve-DnsName

Get-Content ..... | ForEach-Object {
    $status = 'Dead'
    if(Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue) {
        $status = 'Alive'
    }

    $dns = Resolve-DnsName $_ -ErrorAction SilentlyContinue

    [pscustomobject]@{
        Status    = $status
        Target    = $_
        IPAddress = $dns.IPAddress -join ', '
    }
} | Export-Csv ..... -NoTypeInformation

相关问题