简体   繁体   English

为什么PowerShell不引发此异常?

[英]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 . 使用SharePoint API,我一直在研究尝试通过索引器获取不存在的SPList与使用TryGetList相反的TryGetList I had assumed that the indexer throws an exception where TryGetList does not. 我假设索引器会引发一个异常,而TryGetList不会。 This indeed seems to be the case with C#: C#确实确实是这种情况:

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

It throws a ArgumentException with the following Message : 它使用以下Message引发ArgumentException

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

However when I use PowerShell, there is no exception thrown: 但是,当我使用PowerShell时,不会引发任何异常:

$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? 我以为PowerShell只是.NET代码的包装,而索引器本身正在引发异常,但是如果是这种情况,PowerShell也不会引发异常吗? 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. 我知道在许多情况下PowerShell不会抛出C#会抛出的异常,最显着的是在获取空对象的属性时(如我的代码)抛出NullReferenceExceptions,但是我认为这与PowerShell的语法和评估有关。

Does the SharePoint API have special conditions for PowerShell in place in this instance? SharePoint API在此实例中是否具有适用于PowerShell的特殊条件? Or is this something inherant in PowerShell, perhaps ignoring the indexer in order to pass things into the pipeline? 还是这在PowerShell中是固有的,也许会忽略索引器以便将内容传递到管道中? 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? 额外的SharePoint问题-使用PowerShell时,是否有任何理由在Lists索引器上使用TryGetList

You can try to find out what's happening behind the scenes by running Trace-Command cmdlet. 您可以尝试通过运行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. Name参数表示要跟踪的Windows PowerShell组件的名称。 You can get list of trace sources from Get-TraceSource cmdlet and include only necessary ones. 您可以从Get-TraceSource cmdlet 获取跟踪源列表,并且仅包括必要的跟踪源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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