为什么PowerShell没有正确地转换到基类?

3
我试图调用一个需要两个参数的方法。第一个参数是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正确转换类型?我已经查看了Trace-Command TypeConversion,如http://www.powershellatoms.com/powershell-101/casting-values-in-powershell/所述,但没有帮助。

更新:由于众所周知的需求,我提供了实际脚本。我想避免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”。


2
在C#中也是同样的情况。将对象转换为基类并不会对被转换对象做任何实际操作。你想要达到什么目的?请展示你遇到问题的代码。 - user4003407
类型转换不是你的问题。此外,如果ClientContext继承自ClientRuntimeContext,则根本不需要进行类型转换。 - Keith Ripley
1
补充@mchestnut的评论。你从GAC加载Microsoft.SharePoint.ClientMicrosoft.SharePoint.Client.Runtime,并且没有指定程序集版本,你想要加载(LoadWithPartialName已标记为Obsolete,有其原因)。但是Microsoft.SharePoint.Client.WorkflowServices是从文件中加载的,因此它将是特定API版本的程序集,而该特定版本不一定与默认加载的GAC版本匹配。你应该加载所有程序集的相同版本。 - user4003407
1个回答

1
如果我使用“版本16”而不是“版本15”的WorkflowServices程序集,我可以让您的代码正常工作。例如:
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.WorkflowServices.dll"

就这样了。谢谢,马修! - Kirk Liemohn
2
对于那些尽管使用 PowerShell ISE,版本为16且仍无法使其工作的人,请关闭您的 ISE 然后重新启动。 - Radityo Ardi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接