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
  • 509
  • 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
  • 42,571
  • 24
  • 140
  • 158
  • 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
  • 509
  • 1
  • 9
  • 19
  • That command doesn't work for me `Get-Help could not find about_automatic_variables in a help file in this session.` That's PowerShell 3 on Windows 8. – Klas Mellbourn Jun 21 '13 at 15:05
  • @KlasMellbourn, have you run `update-help`? It works for me on v3/Win7. – alroc Jun 21 '13 at 15:54
  • @KlasMellbourn Sorry, I should have added that I was running this on PowerShell 2.0 Also I used the command "Get-Help -Name *" at the end of the list it had HelpFiles that describe a lot of things – Schuyler Jun 21 '13 at 16:53
  • @SSAdministrator no problem, it was my fault since I hadn't updated my help files. – Klas Mellbourn Jun 21 '13 at 17:02
  • 1
    It’s also online at https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables – Tereza Tomcova Jun 13 '19 at 09:51