1
以下PowerShell脚本在重新启动后监视服务器列表,并在它可以附加到Get-Service后立即通知服务器。PowerShell脚本的实时表格输出
#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
但是,关键是要实时显示每个结果。具有讽刺意味的是,脚本顶部的开始输出正是我想要的。
我想加在一起所有的输出为对象,所以我可以将该值传递给另一个脚本。如果我按照你的建议修改输出,它将输出一个带有两列的列表视图。 – user2359792 2013-05-08 14:01:33
我没有看到问题。样本是否不完整(在其他地方是否使用了$ jobsdone)?如果是这样,请使用我答案的第一部分来仅修复可见输出。我删除的唯一东西是不必要的对象创建和'format-table'(BY THE WAY,销毁你刚刚创建的对象)。 – 2013-05-08 16:02:28
只是为了澄清更多。如果将代码保存为脚本并运行它,它将返回对象的ARRAY,您可以将其存储和/或传递给另一个cmdlet/function/script。因此,如果默认视图是列表视图,请运行'myscript.ps1 |“之类的东西format-table -autosize'。只记得不要在代码中使用'format -...'cmdlet,因为它返回一个特殊的formatobject,而不是原始的数据对象本身。 – 2013-05-08 18:02:10