Micael
Micael

Reputation: 59

Why my variable appear empty in Invoke-Command

I made this short script to monitor and, if needed, restart the printer spooler on a few servers

$c = Get-Credential
$servers = 'FQDN1', 'FQDN2', 'FQDN3'
foreach ($s in $servers){
    Invoke-Command -ComputerName $s -Credential $c {$j = (Get-PrintJob -PrinterName 'Test Printer').count
        Write-Host "On computer $s there are $j print jobs"
        If ($j -gt 5){
            Write-Host "About to restart the printer spooler on $s"
            Restart-Service 'Spooler'
        }
    } # end of invoke-command
} # end of foreach

What I don't understand is why the Write-Host does not write the server name ($s), but it writes instead the number of jobs ($j).

I guess it has something to do with the variable being in the remote session but not in the local one. But I can't really understand what exactly is the problem.

Upvotes: 2

Views: 2200

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174760

As of PowerShell 3.0, you can refer to a local variable in a remote session scriptblock with the $using: prefix:

foreach ($s in $servers){
    Invoke-Command -ComputerName $s -Credential $c {
        Write-Host "On computer $using:s now"
    } # end of invoke-command
} # end of foreach

See the about_Remote_Variables helpfile for more information

Upvotes: 4

Martin Brandl
Martin Brandl

Reputation: 58991

You are right, you have to pass the variable to the scriptblock in order to access it.

To do that, you have to define a Param() section at the start of your scriptblock and pass the argument (server) using the -ArgumentList parameter:

$c = Get-Credential
$servers = 'FQDN1', 'FQDN2', 'FQDN3'
foreach ($s in $servers){
    Invoke-Command -ComputerName $s -Credential $c -ScriptBlock {
        Param($s)
        $j = (Get-PrintJob -PrinterName 'Test Printer').count
        Write-Host "On computer $s there are $j print jobs"
        If ($j -gt 5){
            Write-Host "About to restart the printer spooler on $s"
            Restart-Service 'Spooler'
        }
    }  -ArgumentList $s # end of invoke-command
} # end of foreach

Upvotes: 1

Related Questions