以下 powershell 脚本在重新启动后监视服务器列表,并在它可以使用 Get-Service 附加时立即通知。
#start all jobs here
get-job | stop-job
get-job | remove-job
$servers = ("localhost", "127.0.0.1", "badserver")
function Ping-Service($myservers,[int]$timeout=60, [int]$waitbetweentrys=1){
$myservers| %{
$computername = $_
start-job -scriptblock {
param(
[string]$computername,
[int]$maxwait,
[int]$waitbetween
)
$status = "Fail"
$StartTime = Get-Date
$duration = 0
do
{
#if successful, break out
try {$gs = Get-Service -ComputerName $computername -ErrorAction Stop;$status = "Success";break} catch {start-sleep $waitbetween}
$duration = (New-TimeSpan $StartTime $(Get-Date)).Seconds
} while ($duration -lt $maxwait)
$hash = [ordered]@{"Computername" = $computername; "Type" = "Service";"Status"=$status;"Done"=$(Get-Date);"Duration"=$duration}
$hash
} -ArgumentList ($computername, $timeout, $waitbetweentrys)
}
}
Ping-Service -myservers $servers -timeout 10
#loops through jobs and check for completed ones
do
{
#process jobs that are done
$jobsdone = Get-Job | where State -eq 'Completed'
$joboutput = $jobsdone | Receive-Job
$joboutput | %{New-Object PSObject -Property $_ } |ft -AutoSize
#remove jobs once we get the output
$jobsdone | Remove-job
#See if there are any jobs left
$jobsleft = Get-Job
#wait 5 seconds before checking jobs
if ($jobsleft -ne $null) {start-sleep 5}
} while ($jobsleft -ne $null) #continue loop while there are jobs left
它工作得很好,但输出的格式不是我想要的:
Duration Status Computername Done Type
-------- ------ ------------ ---- ----
0 Success localhost 5/7/2013 4:09:30 PM Service
Duration Status Computername Done Type
-------- ------ ------------ ---- ----
0 Success 127.0.0.1 5/7/2013 4:09:31 PM Service
Duration Status Computername Done Type
-------- ------ ------------ ---- ----
10 Fail badserver 5/7/2013 4:09:42 PM Service
我希望它看起来像这样:
Duration Status Computername Done Type
-------- ------ ------------ ---- ----
0 Success localhost 5/7/2013 4:09:30 PM Service
0 Success 127.0.0.1 5/7/2013 4:09:31 PM Service
10 Fail badserver 5/7/2013 4:09:42 PM Service
但是,关键是要实时显示每个结果。具有讽刺意味的是,脚本顶部的 start-job 输出正是我想要的。