繁体   English   中英

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; 尝试,捕捉,是否存在,否则无法理解如何正确使用它。

尝试这个:

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
}

使用-Co​​mputerName属性内部的数组,然后将输出传递到外文件,并不能使您访问-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
}

暂无
暂无

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

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