Powershell using if and exit

Sara 441 Reputation points
2021-05-25T06:41:16.393+00:00

I have the below script to disable the task scheduler job, which should disable the job if it is not disabled, but it exits the window without disabling , what am I missing here? Any thoughts?

if ((Get-ScheduledTask -taskname test | Select-Object -ExpandProperty State) -notmatch "disabled") { exit 1 }
Disable-ScheduledTask -taskname test
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2021-05-25T08:07:46.557+00:00

    Hi @Saravanaraj-6475 ,

    please try this:

    if ((Get-ScheduledTask -taskname test | Select-Object -ExpandProperty State) -notmatch "disabled") {
        Disable-ScheduledTask -taskname test
    }
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten


2 additional answers

Sort by: Most helpful
  1. Anonymous
    2021-05-25T08:47:43.663+00:00

    Hi,

    The PowerShell console exits because of "exit 1". The "exit" keyword makes PowerShell exit the current script or PowerShell instance.

    Exit

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2021-05-25T08:39:47.957+00:00

    @Saravanaraj-6475 ,

    If you like you can use Exit

    if ((Get-ScheduledTask -taskname test | Select-Object -ExpandProperty State) -notmatch "disabled") {  
        Disable-ScheduledTask -taskname test  
        Exit 1  
    }  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.