PowerShell多线程脚本输出格式

时间:2013-11-11 20:32:22

标签: powershell

我在powershell中有一个脚本来命中列表中的每个服务器并检查它是否在线。由于耗费时间,我编写了一个线程逻辑来调用该脚本,我的脚本工作正常。但我想将我的好/坏服务器分成两个不同的文本文件,我不能在我的脚本中硬编码,因为显然资源可能被另一个线程使用。如果我在线程逻辑中写它,我的输出(好的和坏的)将在同一个文件中。任何想法我怎样才能很好地格式化所需的输出。

### Start-MultiThread.ps1 ###
$Servers =Get-Content -Path "C:\Scripts\Servers.txt"

#Start all jobs
ForEach($Server in $Servers){
    Start-Job -FilePath "C:\Scripts\ChkOnline.PS1" -ArgumentList $Server
}

#Wait for all jobs
Get-Job | Wait-Job

#Get all job results
Get-Job | Receive-Job |Out-File -FilePath "C:\Scripts\Output.txt"


##ChkOnline.PS1###

Param($Server = "ServerNameHolder")
$PingStatus= Test-Connection $Server -Quiet

              If ($PingStatus -eq 1)
                        {
                          Return $Server " is online!!"
                        }
            Else
                        {
                          Return $Server " is offline!"
                        }

2 个答案:

答案 0 :(得分:1)

您可以在不启动多个作业的情况下执行此操作。启动多个工作会产生记忆和处理时间开销和这样的任务,它的开销超过了它的价值。

$Servers = Get-Content -Path "C:\Scripts\Servers.txt"
$results = Test-Connection -ComputerName $servers -Count 1 -ErrorAction silentlycontinue;
$AvailableServers = $results|select -expandproperty address
$OfflineServers = Compare-Object -ReferenceObject $Servers -DifferenceObject $AvailableServers -PassThru;
$AvailableServers | out-file c:\scripts\onlineservers.txt;
$OfflineServers | out-file c:\scripts\offlineservers.txt;

答案 1 :(得分:0)

使用-asjob参数(多进程)可以使其非常快。启动的将具有非null的ResponseTime属性。不幸的是,默认情况下,测试连接将ResponseTime属性显示为“ Time(ms)”。目标名称可以是数组。

$servers = 'microsoft.com','yahoo.com'
$a = test-connection $servers -AsJob | Receive-job -Wait -AutoRemoveJob

$a | where responsetime # up

Source        Destination     IPV4Address      IPV6Address  Bytes    Time(ms)
------        -----------     -----------      -----------  -----    --------
DESKTOP-JQ... yahoo.com       98.138.219.231                32       65


$a | where { ! $_.responsetime } # down

Source        Destination     IPV4Address      IPV6Address  Bytes    Time(ms)
------        -----------     -----------      -----------  -----    --------
DESKTOP-JQ... microsoft.com   40.112.72.205                 32
相关问题