Author Posts

November 10, 2015 at 9:05 am

How can I pass "Get-Process" with a function call to a remote computer? I can get results with for example $value = invoke-command -ComputerName $Server -scriptblock {Get-Process | Select-Object -Property Name, CPU}. But I want to create a new variable/table column called on a function. Is this possible?

$CPUPercent = @{
Name = 'CPUPercent'
Expression = {
$TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
[Math]::Round( ($_.CPU * 100 / $TotalSec), 2)
}
}

Get-Process |
Select-Object -Property Name, CPU, $CPUPercent, Description |
Sort-Object -Property CPUPercent -Descending |
Select-Object -First 4

November 10, 2015 at 3:23 pm

Hi mate, If you are using PowerShell version 3.0 or later you can use this method:

say we set out variable in our local session:

$CPUPercent = @{
 Name = 'CPUPercent'
 Expression = {
 $TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
 [Math]::Round( ($_.CPU * 100 / $TotalSec), 2)
 }
 }

Then we can use invoke-command as normal:

 Invoke-Command machine1.domain.com {$Using:CPUPercent} 

We can use the $Using variable to reference locally created variables and pass those into remote scriptblocks.

However in 2.0 this was not an option. Here is how you would pass values in version 2.0 of PowerShell:

Invoke-Command -ComputerName Machine1.domain.com -ScriptBlock {
 $($args[0])

} -ArgumentList $CPUPercent

Hope this helps.

November 10, 2015 at 4:58 pm

...? I'm so confused 😀