【问题标题】:Upgraded output for powershell script升级了 powershell 脚本的输出
【发布时间】:2017-12-19 21:51:48
【问题描述】:

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

计算机.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 和 if,else 但不明白如何正确使用它。

【问题讨论】:

    标签: powershell ip report hostname


    【解决方案1】:

    试试这个:

    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 属性中使用数组,然后将输出转发到 out-file 并不能让您访问 -ComputerName 属性的内容(至少我知道)。将其分解为基本的 foreach 即可。

    【讨论】:

    • 谢谢,真的很管用。但现在它要求每条记录的密码。尝试设置: $username = "company\admin1" $password = cat C:\temp\pass.txt | convertto-securestring $cred = new-object -typename System.Management.Automation.PSCredential ` -argumentlist $username, $password 但是出了点问题。
    • 感谢您的帮助。
    • 感谢您的帮助。这就是它现在的样子:` $mycredentials = Get-Credential Get-Content "c:\Script\computers.txt" | foreach { $job = 调用命令 -credential $mycredentials -ComputerName $_ -ScriptBlock {hostname.exe} 写入输出“$_ $job” |输出文件 "C:\Script\report_hostnames.txt" -Append } `
    • 是的,你明白了,很好!
    【解决方案2】:

    您应该能够使用 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
    }
    

    【讨论】:

    • 感谢您的解决方案,但我无法使用 DNS,因为我将使用主机名信息来清理旧的 DNS 记录。
    • 我们有很多静态记录,我不确定在所有记录上设置当前时间戳是否安全。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多