Powershell - 过滤WMIObject显示两个脚本结果

时间:2016-02-24 05:56:27

标签: powershell wmi start-job

我是powershell的新手,现在我有两个脚本,一个是获取远程服务器的IP,另一个是获取远程服务器的特定服务启动时间,我需要显示远程服务器'的IP和具体的服务开始时间,有人可以指导我如何合并这两个脚本。

下面是我的两个剧本。

$servers = gc -path D:\Ted\Computers.txt

$Job = get-wmiobject win32_networkadapterconfiguration -computer $servers -filter "IPEnabled='True'" -asjob

$results = $job | receive-job

$results


get-job | wait-job

receive-job job* | select IPAddress

另一个获取服务开始时间是

$servers = gc -path D:\Ted\Computers.txt

$check = get-wmiobject win32_process -computer $servers -Filter "Name='aspnet_state.exe'" -asjob

$results = $check | receive-job

$results


get-job | wait-job

receive-job job* | Select-Object name, processId, @{Name="StartTime"; Expression={ $_.ConvertToDateTime( $_.CreationDate )}}

最后我需要知道一件事,如果我对这个脚本使用asjob,那意味着它是多线程执行的?

抱歉我的英语很差,谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

可能有一种更简洁的方法可以做到这一点,但这是我对你的问题的看法。看起来您需要某种方法将每台计算机与两个WMI查询的输出相关联。如果要求使用作业并行运行,则需要更多工作,但这是一个串行版本。

Get-Content -Path D:\Ted\Computers.txt | ForEach-Object {
    $ip = Get-WmiObject Win32_NetworkAdapterConfiguration -Computer $_ -Filter "IPEnabled='True'" | Select-Object IPAddress
    $process = Get-WmiObject Win32_Process -Computer $_ -Filter "Name='aspnet_state.exe'" | Select-Object Name, ProcessId, @{ Name="StartTime"; Expression = { $_.ConvertToDateTime($_.CreationDate) } }

    @{
        Computer = $_
        Ip = $ip
        Name = $process.Name
        ProcessId = $process.ProcessId
        StartTime = $process.StartTime
    }
}

并行版本将是这样的:

# A collection that stores all the jobs
$AllJobs = @()

# A collection that stores jobs correlated with the computer
$ComputerJobs = Get-Content -Path D:\Ted\Computers.txt | ForEach-Object {
    $ipJob = Get-WmiObject Win32_NetworkAdapterConfiguration -Computer $_ -Filter "IPEnabled='True'" -AsJob 
    $AllJobs += $ipJob

    $processJob = Get-WmiObject Win32_Process -Computer $_ -Filter "Name='aspnet_state.exe'" 
    $AllJobs += $processJob

    @{
        Computer = $_
        IpJob = $ipJob
        ProcessJob = $processJob
    }
}

# Wait for everything to complete
Wait-Job -Job $AllJobs

# Iterate the correlated collection and expand the results
$ComputerJobs | ForEach-Object {
    $ip = Receive-Job -Job $_.IpJob | Select-Object IPAddress
    $process = Receive-Job -Job $_.ProcessJob | Select-Object Name, ProcessId, @{ Name="StartTime"; Expression = { $_.ConvertToDateTime($_.CreationDate) } }

    @{
        Computer = $_.Computer
        Ip = $ip
        Name = $process.Name
        ProcessId = $process.ProcessId
        StartTime = $process.StartTime
    }
}