2

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

nice one, didn't knew that +1
Even better. Thank you very much.
1

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

1 Comment

Wonderful. Thank you for the explanation. I'm very grateful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.