Invoke-Command, ScriptBlock, function called withing

Welcome Forums General PowerShell Q&A Invoke-Command, ScriptBlock, function called withing

This topic contains 2 replies, has 3 voices, and was last updated by

 
Participant
3 years, 1 month ago.

  • Author
    Posts
  • #31854

    Participant
    Points: 1
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 2
    Rank: Member

    ...? I'm so confused 😀

The topic ‘Invoke-Command, ScriptBlock, function called withing’ is closed to new replies.