2017-07-14 58 views
0

我正在嘗試編寫將檢查服務器主機名的腳本。 現在我有:爲powershell腳本升級輸出

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;嘗試,趕上,如果,否則,但不明白如何以正確的方式使用它。

回答

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 
} 

使用-Co​​mputerName屬性內的數組,然後管道輸出着出文件不給你一個方法來訪問的-ComputerName屬性的內容(至少我知道的)。把它分解成一個基本的foreach吧。

+0

謝謝,這真的很有用。但現在它要求每個記錄的密碼。 試圖設置: $ username =「company \ admin1」 $ password = cat C:\ temp \ pass.txt | convertto-securestring $ cred = new-object -typename System.Management.Automation.PSCredential' -argumentlist $ username,$ password 但是有些問題。 – Alex

+0

謝謝你的幫助。 – Alex

+0

謝謝你的幫助。 這是它現在的樣子: ' $ mycredentials = Get-Credential Get-Content「c:\ Script \ computers.txt」| foreach {$ job = invoke-command -credential $ mycredentials -ComputerName $ _ -ScriptBlock {hostname.exe} write-output「$ _ $ job」| out-file「C:\ Script \ report_hostnames.txt」-Append } ' – Alex

1

您應該可以使用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 
} 
+0

謝謝你的解決方案,但我不能使用DNS,因爲我打算使用主機名信息來清理舊的DNS記錄。 – Alex

+0

這通常是通過清理來管理的。 –

+0

我們有很多靜態記錄,並且我不確定在所有記錄上設置當前時間戳是否安全。 – Alex