我在远程系统上运行C#PowerShell代码,需要获取局部变量的值。 PowerShell有一个名为Get-Variable
的cmdlet,我正在尝试使用。这是我的代码,用于尝试获取PSVariables的相关集合(显然应该只包含其中一个):
psShell.AddScript($"$text = 'someValue'");
psShell.Invoke();
psShell.Commands.Clear();
psShell.AddCommand("Get-Variable")
.AddParameter("Name", "text");
var v = psShell.Invoke<PSVariable>();
问题在最后一行,我得到以下异常:
Cannot convert the "System.Management.Automation.PSVariable" value of type "Deserialized.System.Management.Automation.PSVariable" to type "System.Management.Automation.PSVariable".
有人知道如何解决这个问题吗?
我也知道StackOverflow上提到的SessionStateProxy方法,但是as this post of mine shows,由于某种原因,它不适用于我的情况。
答案 0 :(得分:1)
涉及PowerShell远程处理时,只有少数几种知名类型会以类型保真度反序列化,System.Management.Automation.PSVariable
不属于其中。
所有其他类型的实例反序列化为原始对象的无方法 emulations ,就像[psobject]
实例具有包含原始属性值的静态副本的属性一样。
在PowerShell中,这些实例将其类型名称报告为以Deserialized.
为前缀的原始类型名称。
有关背景信息,请参见this answer。
处理此类对象的最简单方法是通过DLR:
dynamic v = psShell.Invoke();
然后,您可以照常访问属性(尽管具有运行时绑定),例如v.Name
。