Friday, 15 July 2011

Powershell: Combining Variables in Output -



Powershell: Combining Variables in Output -

i'm trying set simple code outputs server name, lastly reboot date, , difference in hours , days. i've tried several iterations of write-host, can't seem output expect. output should this: servername | reboot date | time running (day, hours)

here code:

begin {} process { foreach($server in (gc d:\win_ip.txt)){ if(test-connection -computername $server -count 1 -ea 0) { $strfqdn = [system.net.dns]::gethostbyaddress($server) | select-object hostname -erroraction "silentlycontinue" $wmi = get-wmiobject -class win32_operatingsystem -computer $server $strdate = $wmi.converttodatetime($wmi.lastbootuptime) $strdiff = [datetime]::now - $wmi.converttodatetime($wmi.lastbootuptime) | format-table days, hours } else { write-verbose "$server offline" } } } end {}

if explain how combining variables works, how format output, i'd appreciate it.

thanks in advance.

try this:

foreach ($server in (get-content "d:\win_ip.txt")){ if (test-connection -computername $server -count 1 -quiet) { $strfqdn = [system.net.dns]::gethostbyaddress($server) $wmi = get-wmiobject -class win32_operatingsystem -computer $server $strdate = $wmi.converttodatetime($wmi.lastbootuptime) $strdiff = [datetime]::now - $strdate [pscustomobject]@{ "servername" = $strfqdn.hostname "reboot date" = $strdate "time running" = "$($strdiff.days) days, $($strdiff.hours) hours" } } else { write-verbose "$server offline" } }

what did store each field in single object, outputted object without formatting it. typically not thought format objects because converted strings , cannot used other outputting host/file.

powershell

No comments:

Post a Comment