Zeno
Zeno

Reputation: 1839

try catch not working with Get-ChildItem

I have this Powershell code:

Function blah
{
...
try
{
    $numct = ( Get-ChildItem "\\devicename\c$\Users\user\Documents\ShareFile\Folders" -ea "Stop" | Measure-Object ).Count;
}
catch
{
    "Error: " + $($_.Exception.Message)
    return $false
}

It works in a successful scenario, but if you say change devicename to a fake device it does not fall into the catch section.

Upvotes: 1

Views: 1498

Answers (1)

briantist
briantist

Reputation: 47832

This code snippet looks like it was originally in a function?

If so the "Error: " + $($_.Exception.Message) line is returning that message as the return value of the function, but it may not display it.

Since it's intended to be displayed it warrants a call to Write-Host, Write-Verbose, Write-Error, etc.

By just using the value alone, you are implicitly calling Write-Object, which in a function returns the object to its caller.

Once you are out all functions, the host decides what to do with it (typically display it). Use one of the above functions to explicitly write text.

Upvotes: 2

Related Questions