Search code examples
powershellif-statementinvoke-command

Powershell Invoke script block - pass proccess check not just text


How can i get: (works)

$Procname = 'notepad'

Invoke-Command -ComputerName sandbox -ScriptBlock {

    if ((Get-Process | Where-Object {$_.Name -eq $Procname}) -eq $null) {
        Write-Host 'null' -ForegroundColor Red
    } else {
        Write-Host running -ForegroundColor Green
    }
}

Too look like this? (no work)

$Procname = 'notepad'
$chk = (Get-Process | Where-Object {$_.Name -eq $Procname})

Invoke-Command -ComputerName sandbox -ScriptBlock {

    if ($chk -eq $null) {
        Write-Host 'null' -ForegroundColor Red
    } else {
        Write-Host running -ForegroundColor Green
    }
}

The trouble i am having is getting the Get-process | where-object to run from outside the scriptblock, I can pass text OK from outside the scriptblock (IE the $Procname) but i am trying to pass the command, what special things do i need to do?

I have asked uncle google, but I think I'm asking the wrong question.

I have also tried $chk as a Param and an arg but they didn't work for me


Solution

  • Ok, it looks like you want to know how to reference a local variable in a remote execution via Invoke-Command. Totally something you can do with the $using: context. For example, to make your script look to see if notepad is running on your computer, and then reference those results on a remote system you could do this:

    $Procname = 'notepad'
    $chk = (Get-Process | Where-Object {$_.Name -eq $Procname})
    
    Invoke-Command -ComputerName sandbox -ScriptBlock {
    
        if ($using:chk -eq $null) {
            Write-Host 'null' -ForegroundColor Red
        } else {
            Write-Host 'running' -ForegroundColor Green
        }
    }
    

    Similarly, if you want to see if notepad is running on the remote server you could do this:

    $Procname = 'notepad'
    
    Invoke-Command -ComputerName sandbox -ScriptBlock {
    
        if ((Get-Process | Where-Object {$_.Name -eq $using:Procname}) -eq $null) {
            Write-Host 'null' -ForegroundColor Red
        } else {
            Write-Host 'running' -ForegroundColor Green
        }
    }
    

    But personally I think that is hard to read, I'd reverse it and do:

    $Procname = 'notepad'
    
    Invoke-Command -ComputerName sandbox -ScriptBlock {
    
        if (Get-Process | Where-Object {$_.Name -eq $using:Procname}) {
            Write-Host 'running' -ForegroundColor Green
        } else {
            Write-Host 'null' -ForegroundColor Red
        }
    }
    

    Or without running anything on the remote server directly:

    $Procname = 'notepad'
    $chk = Get-Process -Computer sandbox | ?{$_.Name -eq $Procname}
    If($chk){
        Write-Host 'Running' -ForegroundColor Green
    }else{
        Write-Host 'Null' -ForegroundColor Red
    }