question

Sara925 avatar image
0 Votes"
Sara925 asked IanXue-MSFT answered

Powershell using if and exit

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-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered Sara925 commented

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

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

It works , but can we also make use of the exit code here ?

0 Votes 0 ·
AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered

@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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
1 Vote"
IanXue-MSFT answered

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.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.