【问题标题】:PowerShell can't catch SharePoint Enable-SPFeature exceptionPowerShell 无法捕获 SharePoint Enable-SPFeature 异常
【发布时间】:2023-03-09 05:59:02
【问题描述】:

尝试在 SharePoint 2010 中启用自定义功能时,我遇到了无法在 PowerShell v2 中以编程方式捕获、捕获或检测的异常。我知道错误是什么以及如何在 Central Admin 中修复它,但我很担心 PowerShell 部署脚本无法识别此错误情况。

# This correctly gets the site and feature:
PS C:\> $Error.Clear()
PS C:\> $SiteUrl = 'http://thesite'
PS C:\> $FeatureId = 'D3BF12C5-D342-4F8A-8E86-BB4308699359'
PS C:\> $Site = Get-SPSite | Where { $_.Url -eq $SiteUrl }
PS C:\> $Feature = Get-SPFeature | Where { $_.Id.ToString() -eq $FeatureId }

# But this line produces the error information below it in the console window - in plain color, not red:
PS C:\> $Feature | Enable-SPFeature -url $SiteUrl
Source: Microsoft.Office.Server.UserProfiles
Message: Users cannot override privacy while the property is replicable.
Trace:    at Microsoft.Office.Server.UserProfiles.ProfileSubtypeProperty.set_UserOverridePrivacy(Boolean value)
       at IHI.Springs.GAC.UserProfile.UserProfilePropertyManager.EnableUserOverridePrivacy(String propertyName)
       at IHI.Springs.GAC.EventReceivers.FeatureReceivers.ProfilePropertyFeatureReceiver.FeatureActivated(SPFeatureReceiverProperties properties)

上面的错误信息已写入控制台,但无法以编程方式检测到:

运行 Enable-SPFeature 命令后,$?是 $true,$Error 没有错误,$LastExitCode 没有。

尝试使用 try/catch 或陷阱捕获异常失败。对于下面的行,错误消息仍然转储到控制台,但“错误捕获!”从不显示:

try { $Feature | Enable-SPFeature -url $SiteUrl } catch { "Error caught!" }    
trap { "Error caught!" } $Feature | Enable-SPFeature -url $SiteUrl

无论我做什么,我都无法捕捉到该文本;这些都不起作用:

控制台显示错误信息,$ErrorInfo 为空:

$ErrorInfo = $Feature | Enable-SPFeature -url $SiteUrl 2>&1
$ErrorInfo = $null; $Feature | Enable-SPFeature -url $SiteUrl -ErrorVariable ErrorInfo

控制台中显示错误消息,ErrorFile.txt 已创建(预期)但为空:

$Feature | Enable-SPFeature -url $SiteUrl > c:\temp\ErrorFile.txt

我们正在研究我们的功能激活代码,并且我们知道如何在服务器上修复此问题,但我无法以编程方式检测到此错误,这太疯狂了。异常由 cmdlet Enable-SPFeature 引发,但 PowerShell 没有将异常包装在 ErrorRecord 中,也没有将其写入错误管道或执行任何有用的操作。自从 Monad Beta 2 发布以来,我一直在相当广泛地使用 PowerShell,并且看到了很多时髦的东西,但这动摇了我对它的信心。 (我对 SharePoint 没有任何信心,所以没有任何损失)。

【问题讨论】:

  • Powershell + Sharepoint 错误处理。不错!

标签: sharepoint powershell


【解决方案1】:

这是一种 WAG,我从未使用过任何 SharePoint cmdlet。

尝试在 Enable-SPFeature 命令中添加“-ea Stop”(不带引号)。这可能会导致实际抛出错误。

IMO,使用 -ea Stop 强制错误成为终止错误,以便它们可以被捕获,这是 PowerShell 更违反直觉的功能之一。

【讨论】:

  • 有效!非常感谢!添加 -ErrorAction 停止时,$?现在是假的,$Error 和 try/catch 中的 $_ 一样有 ErrorRecord。我无法阻止文本输出到控制台(通过任何重定向),也无法填充 ErrorVariable。只要我有错误信息,这没什么大不了的。再次感谢 - 以这种方式使用 -EA 是违反直觉的!
猜你喜欢
  • 2013-09-01
  • 2013-06-25
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多