I have been experimeing with try and catch. I thought if you got an error in the try it would not display or stop the script and then run catch. When I run the following try and catch script it fails with an error and does not run the catch block
Try {
$RegKey ="HKLM:\Software\Policies\something\something"
$version = Get-ChildItem $RegKey -Name
}
catch {
Write-Host "something went wrong"
}
I would expect it to display “something went wrong”, but that is not happening.
You need to specify an erroraction so that a terminating error is thrown. Try the below:
Try {
$RegKey ="HKLM:\Software\Policies\something\something"
$version = Get-ChildItem $RegKey -Name -ErrorAction Stop
}
catch {
Write-Host "something went wrong"
}
ok, but why do I not need one in this code(it displays the catch). what is the difference?
Try {
thiswillfail
}
catch {
Write-Host "something went wrong"
}
Shane,
The ErrorAction has to be set to Stop. There are a lot of blogs and articles on Error handling, see http://blogs.technet.com/b/heyscriptingguy/archive/2014/07/09/handling-errors-the-powershell-way.aspx
try {
$RegKey ="HKLM:\Software\Policies\something\something"
$version = Get-ChildItem $RegKey -Name -ErrorAction Stop
}
catch {
"Error: {0}" -f $_.Exception.Message
}
thiswillfail is not a valid command. Powershell will throw a terminating error because it cannot find a command to execute. In the other scenario, Get-ChildItem is a valid command and can throw an error message to the console that is not a terminating error. This is useful if you have a list of input that you want to keep processing even if one error out, it does not kill the entire process. In the below example, if get-childitem threw a terminating error when it could not find “doesnotexist”, I would not get the returned value for “HelpDeskMenu.ps1”.
PS F:\temp\Powershell> get-childitem
Directory: F:\temp\Powershell
Mode LastWriteTime Length Name
----- 8/6/2015 9:40 AM 979 script-parameter examples.ps1
----- 8/6/2015 11:18 AM 3416 fred.psm1
----- 8/6/2015 11:36 AM 209 HelpDeskMenu.ps1
PS F:\temp\Powershell> “fred.psm1”, “doesnotexist”, “HelpDeskMenu.ps1” | Get-ChildItem
Directory: F:\temp\Powershell
Mode LastWriteTime Length Name
----- 8/6/2015 11:18 AM 3416 fred.psm1
Get-ChildItem : Cannot find path ‘F:\temp\Powershell\doesnotexist’ because it does not exist.
At line:1 char:51
- “fred.psm1”, “doesnotexist”, “HelpDeskMenu.ps1” | Get-ChildItem
-
~~~~~~~~~~~~~
- CategoryInfo : ObjectNotFound: (F:\temp\Powershell\doesnotexist:String) [Get-ChildItem], ItemNotFoundEx
ception
- FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
----- 8/6/2015 11:36 AM 209 HelpDeskMenu.ps1
Thanks for helping clear this up 