I want to write a PowerShell script to select a JFrog service connection, but the script is not behaving the way I expect it to behave.
When I run the jfrog config use
command manually, it works as expected:
PS C:\Users\rdepew> jfrog config use Dummy
[Info] Using server ID 'Dummy' (https://foo.jfrog.io/).
PS C:\Users\rdepew> $?
True
I expect to be able to use the $?, which always returns true or false, to detect whether or not jfrog config use
has executed successfully. This snippet illustrates the problem I've got:
PS C:\Users\rdepew> if (jfrog config use Dummy) {
>> Write-Host Dummy exists
>> } else {
>> Write-Host Dummy doesnt exist but I dont believe it
>> }
[Info] Using server ID 'Dummy' (https://foo.jfrog.io/).
Dummy doesnt exist but I dont believe it
The [Info] line indicates that JFrog is in fact using server connection 'Dummy'. I assume that the $? exit code evaluates as true, just like it did in my manual execution. But my if/else test takes the "if false" branch. Why?
MORE INFO: If I use the name of a nonexistent service connection, I get the expected behavior:
PS C:\Users\rdepew> if (jfrog config use Bogus) {
>> Write-Host Bogus exists
>> } else {
>> Write-Host Bogus doesnt exist
>> }
[Error] Could not find a server with ID 'Bogus'.
Bogus doesnt exist
I don't understand why PS jumps to the else
clause for both True and False cases.
STILL MORE INFO
Thanks to the first answers and comments, I understand a little more. I can rewrite my snippet like this:
jfrog config add Dummy
if ($LASTEXITCODE=0) {
etc.
But I'm still confused about $? behavior. From the command line, $? behaves like this:
PS C:\Users\rdepew> jfrog config use Dummy
[Info] Using server ID 'Dummy' (https://foo.jfrog.io/).
PS C:\Users\rdepew> $?
True
PS C:\Users\rdepew> jfrog config use Bogus
[Error] Could not find a server with ID 'Bogus'.
PS C:\Users\rdepew> $?
False
... which is what one would expect.