简体   繁体   中英

Why does PowerShell not throw this exception?

Using the SharePoint API, I have been investigating the difference between attempting to get an SPList that does not exist via the indexer as opposed to with TryGetList . I had assumed that the indexer throws an exception where TryGetList does not. This indeed seems to be the case with C#:

SPSite site = new SPSite("http://urlofsite");
Console.WriteLine(site.RootWeb.Lists["hello"].Title);

It throws a ArgumentException with the following Message :

List 'hello' does not exist at site with URL 'http://urlofsite'.

However when I use PowerShell, there is no exception thrown:

$site = Get-SPSite http://urlofsite
$site.RootWeb.Lists["hello"].Title

I had assumed that PowerShell was just a wrapper for the .NET code, and that the indexer itself was throwing the exception, but if this was the case, wouldn't PowerShell throw the exception too? I am aware of many situations where PowerShell does not throw exceptions where C# does, most notably NullReferenceExceptions when getting properties on null objects (as in my code) but I thought that was all to do with PowerShell's syntax and evaluation.

Does the SharePoint API have special conditions for PowerShell in place in this instance? Or is this something inherant in PowerShell, perhaps ignoring the indexer in order to pass things into the pipeline? That doesn't seem right either though... What am I misunderstanding?

Bonus SharePoint question - is there any reason to use TryGetList over the Lists indexer when using PowerShell?

You can try to find out what's happening behind the scenes by running Trace-Command cmdlet.

For example:

Trace-Command -Expression {$site.RootWeb.Lists["hello"].Title} -PSHost -Name *

The Name parameter means names of Windows PowerShell components to be traced. You can get list of trace sources from Get-TraceSource cmdlet and include only necessary ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM