Stephen Sugumar
Stephen Sugumar

Reputation: 545

Powershell - Extract Variable from Pipe

This is my first time working with Powershell and I need some help on a query.

I need to remote connect to some servers on a common domain and extract memory consumption from each server, then display them into a Text file. All this is working with this query:

$serverList = @("DMOBBQ-008","DCOBF1-003","DCOBF1-013","DCOBF2-005","DCOBF2-006","DCOBF2-007","DCOBF2-015","DMOBB8-007","DMOBBE-000","DMOBBQ-005","DMOBBQ-006","DMOBBQ-007","DMOBBR-007","DMOBC4-002","DMOBBR-005","DCOBBN-D06")


ForEach($server in $serverList)
{
    Write-Host $server":"
    $results = (get-process w3wp -computername $server | where-object {$_.privatememorysize -gt 1000000000} | select name, @{l="Private Memory (GB)"; e={$_.privatememorysize / 1gb}}) 
    #Write-Host $results 
    $highMem = $results | ? { $_.'Private Memory (GB)' -gt 1.6 }
    Write-Host $highMem
}

#out-file -filepath C:\Memory_Script\Results.txt -inputobject $mem -encoding ASCII -width 50

My question is: I need to hold the memory value obtained from each server. From there, I need some logic to determine if the memory is above 1.6GBs, and display a list of servers in this standing at the top of the text file.

How can I go about this?

Another question, I copied some of the query from some tutorials, why is the "e=" in this part of the query?

e={$_.privatememorysize / 1gb}

Thank you for your time.

Upvotes: 2

Views: 262

Answers (2)

arco444
arco444

Reputation: 22871

To answer your first question, it would be best to have an array of objects. Your current command returns an object with various properties. To do this for multiple servers you just need to create $results as an array and append to it for each server.

Assuming you somehow populate $servers with the correct list:

$servers = Get-Content ".\list-of-servers.txt"
$results = @()

foreach($server in $servers) {
  $results += ,(get-process w3wp -computername $server | where-object {$_.privatememorysize -gt 1000000000} | select name, @{l="Private Memory (GB)"; e={$_.privatememorysize / 1gb}}) 
}

$highMem = $results | ? { $_.'Private Memory (GB)' -gt 1.6 }

$results contains a list of all the servers, you can then filter it as shown to get processes where the memory is > 1.6.

To answer your second question, the e={$_.privatememorysize / 1gb} is a way of performing a calculation on a property of the object and saving it as new property. It is usually used to make things more readable, as shown in your case. The l="Private Memory (GB)" is used to create the label for the calculated property.

Upvotes: 2

Mike Shepard
Mike Shepard

Reputation: 18176

The e is short for Expression. l stands for Label.

Upvotes: -1

Related Questions