The Computer Oracle

Why is my if statement always false?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization

--

Chapters
00:00 Why Is My If Statement Always False?
00:36 Accepted Answer Score 82
01:19 Thank you

--

Full question
https://superuser.com/questions/1531588/...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#windows #powershell #script

#avk47



ACCEPTED ANSWER

Score 82


An if statement does not evaluate whether the command inside its condition ran successfully. It will only check the value (in your case the return of your command) and cast it to a bool.

Copy-Item does not return anything by default, and that's why your if statement is always false, because [bool]$null is $false.

You have three options here:

Add the -PassThru parameter to get some form of return:

if (Copy-Item .\test.ps1 $env:SystemRoot\System32 -PassThru)

Use the $? variable to see if your previous command was successful:

Copy-Item .\test.ps1 $env:SystemRoot\System32
if ($?) {
    Write-Host "Done."
    exit 0
}
else {
    Write-Host "Not done."
    Write-Host "You must be root."
    exit 1
}

However, the most reliable way would be to wrap it in Try {} Catch {} and add -ErrorAction Stop

Try {
    Copy-Item .\test.ps1 $env:SystemRoot\System32 -ErrorAction Stop
    Write-Host "Done."
    exit 0
}
Catch {
    Write-Host "Not done."
    Write-Host "You must be root."
    exit 1
}