开发者

Using script in automated build process

开发者 https://www.devze.com 2023-01-30 16:50 出处:网络
I have a Powershell script written, which will be used in an automated build process. Do I need to write exit code 0 when the script will take the correct path (e.g. doesn\'t go into the if blocks wh

I have a Powershell script written, which will be used in an automated build process.

Do I need to write exit code 0 when the script will take the correct path (e.g. doesn't go into the if blocks which indicate an error condition)?

开发者_如何转开发

Also, what is the difference between exit (with code) and $host.SetShouldExit()?


In similar scenario I rely on exceptions (throw) and other kind of terminating errors: the PowerShell’s exit code is 1 in that case. If a scripts finishes itself (even with not terminating errors) then PowerShell’s exit code is 0, we do not have to call exit 0. If we need something but 0 and 1 then indeed we have to use exit or SetShouldExit (but see remarks below).

Let’s take a look at the scripts.

test1.ps1

'before2'
.\test2
'after2'

'before3'
.\test3
'after3'

'before4'
.\test4
'after4'

test2.ps1

'inner before 2'
exit 2
'inner after 2'

test3.ps1

'inner before 3'
$host.SetShouldExit(3)
'inner after 3'

test4.ps1

throw 'Oops'

Output of the test1.ps1:

before2
inner before 2
after2
before3
inner before 3
inner after 3
after3
before4
Oops
At ...
+ throw <<<<  'Oops'

In this test scenario the test4.ps1 kind of works and test2.ps1 and test3.ps1 kind of do not work (if to work means to fail and exit the session immediately).

The output shows that exit terminates the current script and SetShouldExit does not.

The exit code of powershell.exe .\test1 is 3 due to $host.SetShouldExit(3). I have tried to disable that line to check whether exit 2 makes the exit code to be 2. No, it does not, the exit code is 1 due to the failure in test4.

I have noticed one more difference. If I call a script from the interactive PowerShell console than $host.SetShouldExit in a script makes the console to close after the call. exit does not.

A thought. Behaviour of $host.SetShouldExit may depend on implementation of a host. For example, in one my own host exit is not supported at all (it is not allowed to close the hosting application just like that) and my implementation of SetShouldExit basically does nothing at all.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号