6

I'm very new to PowerShell. While looking up information about error handling I've found a lot of references to using "$?"

I know that it has something to do with errors but what exactly is it? And where can I read more about it?

All of my Google searches have found nothing.

Schuyler
  • 489
  • 1
  • 9
  • 19
  • Related post: http://stackoverflow.com/questions/10666035/powershell-difference-between-and-lastexitcode –  Jun 21 '13 at 14:59

2 Answers2

11

From the The Essential Windows PowerShell Cheat Sheet:

Errors and Debugging: The success or failure status of the last command can be determined by checking $?

Example:

> Get-Content file-that-exists.txt
Hello world
> Write-Host $?
True
> Get-Content file-that-does-not-exist.txt
Get-Content : Cannot find path 'C:\file-that-does-not-exist.txt' because it does not exist.
At line:1 char:1
+ Get-Content file-that-does-not-exist.txt
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\file-that-does-not-exist.txt:String) [Get-Content], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
> Write-Host $?
False
Klas Mellbourn
  • 39,060
  • 21
  • 132
  • 151
  • Do you know of any place that has more documentation on it? Or is it just that simple that it doesn't need more documentation? – Schuyler Jun 21 '13 at 15:01
  • 1
    @SSAdministrator it is that easy, its boolean. So you can use it in all sorts of fun ways, like `If (!($?)) {Create-File $SomeFile} – Austin T French Jun 21 '13 at 18:36
2

Just after asking this I discovered the command "Get-Help -name about_automatic_variables"

This gives information about every automatic variable in powershell, it's very helpful

Schuyler
  • 489
  • 1
  • 9
  • 19