powershell 脚本的升级输出

Upgraded output for powershell script

我正在尝试编写将检查服务器主机名的脚本。 现在我有:

Computers.txt

    192.168.10.10
    192.168.10.11
    192.168.10.12

和脚本:

    $servers = get-content "C:\Script\computers.txt"
Invoke-Command -Credential company\admin1 -ComputerName $computers -scriptblock {[Environment]::GetEnvironmentVariable("ComputerName")} | out-file C:\Script\report_hostnames.txt

我有报告:

Computer1
Computer2
Computer3

你能帮我添加IP地址来报告,以及错误状态,像这样:

192.168.10.10 Computer1
192.168.10.11 Computer1
192.168.10.12 Computer Unavailable

我试过了:foreach; try, catch and if, else 但无法理解如何以正确的方式使用它。

试试这个:

get-content "C:\Script\computers.txt" | foreach {
  $Response = Invoke-Command -Credential company\admin1 -ComputerName $_ -scriptblock {[Environment]::GetEnvironmentVariable("ComputerName")} 

  write-output "$_ $Response" | out-file C:\Script\report_hostnames.txt
}

在 -ComputerName 属性中使用一个数组,然后将输出转发到输出文件并不能为您提供访问 -ComputerName 属性内容的方法(至少我知道)。将它分解成一个基本的 foreach 就可以了。

您应该能够使用 DNS 查找主机名。示例:

Get-Content "IPAddresses.txt" | ForEach-Object {
  $outputObject = [PSCustomObject] @{
    "IPAddress" = $_
    "HostName"  = $null
  }
  try {
    $outputObject.HostName = [Net.Dns]::GetHostEntry($_).HostName
  }
  catch [Management.Automation.MethodInvocationException] {
    $outputObject.HostName = $_.Exception.InnerException.Message
  }
  $outputObject
}