Better way of writing a script to avoid boolean error

Tags: powershell

I have written a script and as part of the script I am checking if a job is running and if it is, forcing it to stop:

$copyjob = Get-Job -Name DBACopy_QFR1-DBA20_2_QFR3-DBS21_S_Drv_DBA -ErrorAction SilentlyContinue
if ($copyjob)
    remove-job $copyjob -force   # This job my be causing problems with the backups so we kill it to make sure.

However, I think what I have written is the cause of this error when the script runs:

Cannot convert value "System.Management.Automation.PSRemotingJob" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0

Is there a better way of doing it that doesn't throw up that error, or am I completely incorrect in thinking that this is what is spawning the error.

Instead of

if ($copyjob)

try using

if ($copyjob -ne $null)

If that is all your code does, you can simplify that:

Remove-Job -Name DBACopy_QFR1-DBA20_2_QFR3-DBS21_S_Drv_DBA -ErrorAction SilentlyContinue

Less code, less chances to fail. You can also pipeline:

Get-Job -Name "SomeName" -ErrorAction SilentlyContinue | remove-job -force

This video can help you solving your question :)
By: admin