Invoke-Command, ScriptBlock, function called withing

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Mark Hammonds Mark Hammonds 1 year, 2 months ago.

  • Author
    Posts
  • #31854
    Profile photo of Adam McGill
    Adam McGill
    Participant

    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

  • #31871
    Profile photo of Flynn Bundy
    Flynn Bundy
    Participant

    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.

  • #31877
    Profile photo of Mark Hammonds
    Mark Hammonds
    Participant

    ...? I'm so confused 😀

You must be logged in to reply to this topic.