I have two functions in my powershell script
check_python which checks if python exists in my computer
is_git_repo which checks the current working dir in git repository
I have problem executing this powershell script
$REMOTE_URL = git config --get remote.origin.url
Function check_python{
$python_version = python --version
$python_version
if ( $LASTEXITCODE -eq 0 ){
write-host ("Python is installed with version $python_version")
}else {
write-host ("Kindly install python")
exit 1
}
}
Function is_git_repo {
$REMOTE_URL >$null
if ( $LASTEXITCODE -eq 0 ){
write-host ("Running in git repo")
} else{
write-host ("It's not a Git repo")
exit 1
}
}
check_python
is_git_repo
Executing the above powershell script in non git repo gives me Running in git repo output, Ideally executing is_git_repo function in a non git repo should return exit code 1 but it doesn't
But when I comment out the check_python function it gives me the correct output, I don't know what's this weird behavior.
If you run the script above the git command will run immediately, setting the lastexitcode before you run your functions. The output of your command will be the value of the variable. So, $REMOTE_URL >$null
will just redirect your previously generated output to null, which will always be successful.
You should either move the command inside of the function or change the if to evaluate your variable.
Try something like this:
Function check_python{
$python_version = python --version
$python_version
if ( $LASTEXITCODE -eq 0 ){
write-host ("Python is installed with version $python_version")
}else {
write-host ("Kindly install python")
exit 1
}
}
Function is_git_repo {
$REMOTE_URL = git config --get remote.origin.url
if ( $LASTEXITCODE -eq 0 ){
write-host ("Running in git repo")
} else{
write-host ("It's not a Git repo")
exit 1
}
}
check_python
is_git_repo