Foreach loop output DateTime object plus other details.

I'm having trouble getting a Powershell Foreach loop to output the [DateTime] object so that I can compare it with another object after rebooting.

The script example below, I am looking to create a hash table to save the Computername + Last reboot time, and then add the current reboot time so that it can compare the reboot time.

 $servers = GC D:\Scripts\list1.txt foreach($server in $servers){ Try{ $operatingSystem = Get-WmiObject Win32_OperatingSystem -ComputerName $server $current = [Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime) "$server last rebooted $current" }#end try Catch{ $err = $_.Exception.GetType().FullName Write-Warning "$err on $($server)"}#end catch }#End foreach 

-Edit, the above script outputs below as a string. I am trying to get a collection of TypeName: System.DateTime objects.

 Server1 last rebooted 10/24/2015 11:39:34 Server2 last rebooted 10/22/2015 01:34:33 

Thus, I chatted more and more and got this line, essentially the script becomes "Restart computers until everything becomes relevant."

 IF($current -gt ((Get-Date).AddHours(-6))) {"Server reboot is current for $server"}ELSE{"Please check $server"} 
-1
source share
1 answer

The reason I tried using a hash table or PSCustomObject.

Is it not possible?

 $servers = Get-Content "D:\Scripts\list1.txt" $servers | ForEach-Object{ $props = @{} $props.Server = $_ Try{ $operatingSystem = Get-WmiObject Win32_OperatingSystem -ComputerName $props.Server $props.LastBootTime = [Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime) } Catch { $err = $_.Exception.GetType().FullName $props.LastBootTime = $null Write-Warning "$err on $($props.Server)" }#end catch New-Object -TypeName psobject -Property $props }#End foreach 

Change the structure of the cycle, because if possible, the flow will be piped. Create a hash table for each loop that is converted to an object after the try / catch block. Unverified, but it should work.

+1
source

Source: https://habr.com/ru/post/975852/


All Articles