问题描述
我无法获取Powershell Foreach
循环输出 [DateTime]
对象,所以我可以比较在另一个对象重新启动之后。
I'm having trouble getting a Powershell Foreach
loop to output a [DateTime]
object so I can compare it with another object after rebooting.
下面的示例脚本,我正在寻找创建一个哈希表来存储Computername +上次重新启动时间,然后添加当前的重新启动时间,以便重新启动次数可以比较。
Example script below, I'm looking to create a hashtable to store the Computername + Last reboot time then add a current reboot time so the reboot times can be compared.
$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,上述脚本以字符串形式输出以下内容。我试图收集一个 TypeName:System.DateTime
对象的集合。
-Edit, the above script outputs the below as a string. I'm 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
所以我戳了更多,得到这一行,本质上该脚本变成重新启动计算机,直到一切都是最新的。
So I poked around more and got this line, essentially the script becomes "Reboot the computers until everything is current."
IF($current -gt ((Get-Date).AddHours(-6)))
{"Server reboot is current for $server"}ELSE{"Please check $server"}
推荐答案
不能同时使用!
$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
更改循环结构,因为输出更容易如果需要的话。为try / catch块后转换成对象的每个循环遍建立散列表。未测试,但它应该工作。
Change the loop structure as it is easier for output to be piped if need be. Build a hashtable for each loop pass that is converted into an object after the try/catch block. Untested but it should work.
这篇关于Foreach循环输出DateTime对象加上其他细节。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!