Home > OS >  How add information from another Powershell output
How add information from another Powershell output

Time:12-20

I need some help.

For example, i need to get some information from AD computer.I use something like this:

$computers=Get-ADComputer -Filter {enabled -eq "true"} -Properties name,IPv4Address,OperatingSystem | Select-Object name,created,IPv4Address,OperatingSystem

Then, i do somethig with this computers:

Invoke-Command -computername $computers.name -ScriptBlock {get-hotfix -Description security*} -ErrorAction SilentlyContinue| select-object pscomputername,hotfixid

But i dont understand, how can i merge information from AD and my output. For example i need to get out string or file like that:

Computername(from AD), OperatingSystem (from AD), hotfixid (from my invoke command)

Thx

CodePudding user response:

I would personally do something like this, using Group-Object to get a hashtable for lookup, where the Keys are the computer's Name property would improve the execution time of your script.

One thing to note, I would advice you against using a scriptblock on the -Filter parameter of the ActiveDirectory Module Cmdlets. See this as an example of things that can happen.

$computers = Get-ADComputer -Filter "Enabled -eq '$true'" -Properties IPv4Address, OperatingSystem

$map = Invoke-Command $computers.Name -ScriptBlock {
    Get-Hotfix -Description security*
} -ErrorAction SilentlyContinue |
Group-Object PSComputerName -AsHashTable -AsString

$outObject = {
    param($computer, $id)

    [pscustomobject]@{
        Name = $computer.Name
        IPv4Address = $computer.IPv4Address
        OperatingSystem = $computer.OperatingSystem
        HotFixID = $id
    }
}

foreach($computer in $computers)
{   
    if(-not ($hotfix = $map[$computer.Name]))
    {
        & $outObject -computer $computer -id $null
        continue
    }

    foreach($id in $hotfix.HotFixID)
    {
        & $outObject -computer $computer -id $id
    }
}

Note that, Get-HotFix has a [-ComputerName <String[]>] parameter, untested but in this case, Invoke-Command might not be needed.

CodePudding user response:

Using -pv or -pipelinevariable. But then invoke-command won't run in parallel unless you use foreach-object -parallel in powershell 7.

get-adcomputer a002 -property operatingsystem -pv comp | 
  % { invoke-command $_.name { get-hotfix } } | 
  select pscomputername, @{n='OperatingSystem';e={$comp.operatingsystem}}, 
  hotfixid

PSComputerName OperatingSystem       HotFixID
-------------- ---------------       --------
A002           Windows 10 Enterprise KB5006365
A002           Windows 10 Enterprise KB4562830
A002           Windows 10 Enterprise KB4570334
  • Related