【问题标题】:Why isn't PowerShell properly casting to the base class?为什么 PowerShell 不能正确转换为基类?
【发布时间】:2015-10-22 04:25:09
【问题描述】:

我正在尝试调用需要两个参数的方法。第一个参数是 ClientRuntimeContext。我只有一个ClientContext,但该类继承自ClientRuntimeContext。如果我调用该方法,我会收到以下错误:

New-Object : 找不到“”的重载和参数计数:“2”。

所以,我认为我需要先投射对象。在投射之前,如果我查看 $clientContext.GetType().Name 它会返回“ClientContext”。这是我尝试过的两个强制转换表达式:

$clientRuntimeContext = $clientContext -as [Microsoft.SharePoint.Client.ClientRuntimeContext]
$clientRuntimeContext = [Microsoft.SharePoint.Client.ClientRuntimeContext]$clientContext

不幸的是,在这两种情况下,$clientRuntimeContext.GetType().Name 返回“ClientContext”而不是“ClientRuntimeContext”,我认为这是我的问题的根源。

有没有办法强制 PowerShell 正确转换?我已经查看了http://www.powershellatoms.com/powershell-101/casting-values-in-powershell/ 中描述的 Trace-Command TypeConversion,但这并没有帮助。

更新:由于大众需求,我提供了实际脚本。我想避免 CSOM 和 SharePoint Online 的复杂性,但这可能是问题的一部分。这是脚本。

$SPClient = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$SPClientRuntime = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
Add-Type -Path “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.WorkflowServices.dll”

$siteUrl = "https://tenant.sharepoint.com"
$username = "user@tenant.onmicrosoft.com"
$password = Read-Host -Prompt "Enter Password" -AsSecureString

$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password) 
$clientContext.Credentials = $credentials

$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery()

$webWFAssociations=$web.WorkflowAssociations
$clientContext.Load($webWFAssociations)
$clientContext.ExecuteQuery()

$clientRuntimeContext = $clientContext -as [Microsoft.SharePoint.Client.ClientRuntimeContext]
$WFServicesManager =New-Object Microsoft.SharePoint.Client.WorkflowServices.WorkflowServicesManager($clientRuntimeContext, $clientContext.Web)

最后一行是失败的错误:New-Object:找不到“WorkflowServicesManager”的重载和参数计数:“2”。

【问题讨论】:

  • C# 也是如此。转换为基类实际上不会对转换的对象做任何事情。你想要完成什么?显示代码,你有问题。
  • 类型转换不是你的问题。此外,如果 ClientContext 继承自 ClientRuntimeContext,则根本不需要进行类型转换。
  • 添加到@mchestnut 评论。你从 GAC 加载 Microsoft.SharePoint.ClientMicrosoft.SharePoint.Client.Runtime 并且你没有指定程序集版本,你想加载(LoadWithPartialName 标记为 Obsolete 是有原因的)。但是Microsoft.SharePoint.Client.WorkflowServices 您是从文件加载的,因此它将是特定 API 版本的程序集,并且该特定版本不必匹配 GAC 版本,默认加载。您应该加载所有程序集的相同版本。

标签: powershell casting


【解决方案1】:

如果我使用 WorkflowServices 程序集的“版本 16”而不是“版本 15”,我可以让您的代码正常工作。例如:

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.WorkflowServices.dll"

【讨论】:

  • 就是这样。谢谢,马修!
  • 对于那些尽管您的版本是 16 并使用 PowerShell ISE 却无法完成这项工作的人,请关闭您的 ISE,然后重新开始。
猜你喜欢
  • 2016-08-15
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
相关资源
最近更新 更多