【问题标题】:How to return an object from PowerShell to C# [closed]如何将对象从 PowerShell 返回到 C# [关闭]
【发布时间】:2012-07-26 15:57:01
【问题描述】:

我想将一个对象从 PowerShell 返回到 C#,因此 C# 使用 C# 代码中的对象来调用任何方法并从对象中获取属性。

例如,我有一个 PowerShell 脚本,它使用来自 pshyperv.codeplex.com 的 Hyper-V 模块从主机获取虚拟机。 (这个GetVM.ps1只是一个例子,用于解释返回对象)。

一旦我从 Execute() 执行 PowerShell 脚本,然后它返回对象,我想从 ttt() 调用对象的任何方法。

  1. 是否有可能的解决方案将对象从 PowerShell 返回到 C#?
  2. 如果您发现(PowerShell、C#),您能否更正我的示例代码中的错误?

PowerShell

Param (
    [String]
    $vmHost = '.',
    [String]
    $vmName
)
Process{
    $private:scriptname = $local:myInvocation.MyCommand.Name
    if  (($vmHost -eq '.' ) -and ($vmName -eq 'ITE'))
    {
        #Write-Output "Executing $private:scriptname on $vmHost"
    }
    try {
        return (Get-VM -Name $vmName -Server $vmHost)
    } catch {Write-Error "Unable to create a VM: $vmName"}
}

C#

public void ttt()
{
    ...
    ret = ps.Execute(rs, "GetVM.ps1 -vmName 'ITE*' |out-string");

    Trace.WriteLine(ret[0].Name);
}


public object Execute(Runspace runSpace, string command)
{
    bool error = false;
    StringBuilder retStr = new StringBuilder();

    pipeline.Commands.AddScript(command);

    Collection<PSObject> results = pipeline.Invoke();

    foreach (object item in pipeline.Error.ReadToEnd())
    {
        error = true;
        strOutput.AppendLine(item.ToString());
        retStr.Append(item.ToString());
    }

    foreach (PSObject obj in results)
    {
        strOutput.AppendLine(obj.ToString());
        retStr.Append(obj.ToString());
    }

    strOutput.Append("\r\n");

    return results;
}

执行 PowerShell 结果:

PS C:\CVS\IteExtensionCode\Virtualization\VirtualizationTest\Tools\Virtualization\Hyper-V\W2K8> .\GetVM.ps1 -vmName 'ITE*'  |gm


   TypeName: System.Management.ManagementObject#root\virtualization\Msvm_ComputerSystem

Name                          MemberType    Definition
----                          ----------    ----------
VMElementName                 AliasProperty VMElementName = ElementName
RequestStateChange            Method        System.Management.ManagementBaseObject RequestStateChange(System.UInt16 RequestedState, System.String TimeoutPer...
SetPowerState                 Method        System.Management.ManagementBaseObject SetPowerState(System.UInt32 PowerState, System.String Time)
AssignedNumaNodeList          Property      System.UInt16[] AssignedNumaNodeList {get;set;}
Caption                       Property      System.String Caption {get;set;}
CreationClassName             Property      System.String CreationClassName {get;set;}
Dedicated                     Property      System.UInt16[] Dedicated {get;set;}
Description                   Property      System.String Description {get;set;}
ElementName                   Property      System.String ElementName {get;set;}
EnabledDefault                Property      System.UInt16 EnabledDefault {get;set;}
EnabledState                  Property      System.UInt16 EnabledState {get;set;}
HealthState                   Property      System.UInt16 HealthState {get;set;}
IdentifyingDescriptions       Property      System.String[] IdentifyingDescriptions {get;set;}
InstallDate                   Property      System.String InstallDate {get;set;}
Name                          Property      System.String Name {get;set;}
NameFormat                    Property      System.String NameFormat {get;set;}
OnTimeInMilliseconds          Property      System.UInt64 OnTimeInMilliseconds {get;set;}
OperationalStatus             Property      System.UInt16[] OperationalStatus {get;set;}
OtherDedicatedDescriptions    Property      System.String[] OtherDedicatedDescriptions {get;set;}
OtherEnabledState             Property      System.String OtherEnabledState {get;set;}
OtherIdentifyingInfo          Property      System.String[] OtherIdentifyingInfo {get;set;}
PowerManagementCapabilities   Property      System.UInt16[] PowerManagementCapabilities {get;set;}
PrimaryOwnerContact           Property      System.String PrimaryOwnerContact {get;set;}
PrimaryOwnerName              Property      System.String PrimaryOwnerName {get;set;}
ProcessID                     Property      System.UInt32 ProcessID {get;set;}
RequestedState                Property      System.UInt16 RequestedState {get;set;}
ResetCapability               Property      System.UInt16 ResetCapability {get;set;}
Roles                         Property      System.String[] Roles {get;set;}
Status                        Property      System.String Status {get;set;}
StatusDescriptions            Property      System.String[] StatusDescriptions {get;set;}
TimeOfLastConfigurationChange Property      System.String TimeOfLastConfigurationChange {get;set;}
TimeOfLastStateChange         Property      System.String TimeOfLastStateChange {get;set;}
__CLASS                       Property      System.String __CLASS {get;set;}
__DERIVATION                  Property      System.String[] __DERIVATION {get;set;}
__DYNASTY                     Property      System.String __DYNASTY {get;set;}
__GENUS                       Property      System.Int32 __GENUS {get;set;}
__NAMESPACE                   Property      System.String __NAMESPACE {get;set;}
__PATH                        Property      System.String __PATH {get;set;}
__PROPERTY_COUNT              Property      System.Int32 __PROPERTY_COUNT {get;set;}
__RELPATH                     Property      System.String __RELPATH {get;set;}
__SERVER                      Property      System.String __SERVER {get;set;}
__SUPERCLASS                  Property      System.String __SUPERCLASS {get;set;}
ConvertFromDateTime           ScriptMethod  System.Object ConvertFromDateTime();
ConvertToDateTime             ScriptMethod  System.Object ConvertToDateTime();


PS C:\CVS\IteExtensionCode\Virtualization\VirtualizationTest\Tools\Virtualization\Hyper-V\W2K8> .\GetVM.ps1 -vmName 'ITE*'

Host                      VMElementName             State        Up-Time (mS) Owner
--------                  -------------             -----        ------------ -----
T06CORE                   ITE                       Stopped      0
T06CORE                   ITE2                      Stopped      0

【问题讨论】:

  • “你能纠正一些错误吗”:请告诉我们出了什么问题:它是否无法编译?它在运行时会出错吗?不要使用猜测。
  • 我没有得到正确的返回值。我想知道如何将对象从 powershell 返回到 c#?我想返回 'get-vm' 的对象,但 c# 似乎没有得到结果。 :-(
  • 请告诉我们pipeline.Invoke的返回包含什么? (换句话说,展示你到目前为止的工作:你在调试中遇到了什么问题?)
  • 我得到了截图。
  • 它看起来返回的不是对象。

标签: c# powershell virtualization hyper-v


【解决方案1】:

看起来你有一个 PSObject 包装一个字符串:这看起来是正确的(给定你正在使用的 out-string)。您需要从 PSObject 及其 BaseObject5 属性中提取字符串。

如果您期望 Get-VM 返回的对象集合,请不要使用 Out-String

【讨论】:

  • 同时,您知道如何使用这些对象吗?我得到了对象,但无法调用方法或从其中一个对象获取属性。例如,无法从 VM 对象中获取名称。
  • ret = ps.Execute(rs, "GetVM.ps1 -vmName 'ITE*'");集合 结果 = (Collection)ret; foreach (PSObject obj in results) { 如何调用 obj 的任何方法?调试不显示任何方法,但显示 'BaseObject'、'ImmediateBaseObject' 等属性。它不像 .\GetVM.ps1 -vmName 'ITE*' |gm }
  • 它显示'BaseObject'、'ImmediateBaseObject'、'Members'、'Methods'、'Properties'、'TypeNames'。有没有办法提取方法?
  • @spark 您需要阅读 PowerShell 的“扩展类型系统”(Stack Overflow 答案太多了)。 MSDN 以前的页面似乎已经消失,但在搜索引擎上获得了大量点击。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 2014-11-03
  • 2013-01-15
  • 2011-10-06
相关资源
最近更新 更多