$? Error Handling

by slash85 at 2012-08-29 02:34:08

Hi All,

I’ve got a simple ftp function setup as below, however $? is always returned as “TRUE” is there anything obvious i’m doing wrong? :

[script=powershell]function sendFTP

$ftp = “ftp://user:pass@myserver/upload/slash.txt
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
$webclient.UploadFile($uri, “slash.txt”)

IF ($? -eq “TRUE”) {




Many Thanks for anyhelp,
by poshoholic at 2012-08-29 06:11:42
When checking the value of a boolean such as $? to see if it is true, you need to either compare it against the $true variable, like this:

[script=powershell]if ($? -eq $true) {…}[/script]
or simply test for true like this:

[script=powershell]if ($?) {…} # This will only pass if $? is true[/script]
If you are testing against $false you can compare it to $false, like this:

[script=powershell]if ($? -eq $false) {…}[/script]

or you can use the -not operator like this:

[script=powershell]if (-not $?) {…}[/script]
Both of these will allow you to see if $? is currently set to $false.

Always use $true or $false, never “TRUE” or “FALSE”. The reason is because both “TRUE” and “FALSE” will both convert to boolean $true. In fact, any non-empty string will convert to boolean $true and any empty string or null string will convert to boolean $false.