Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'd like to return an object from Powershell to C#, so c# uses the object inside the C# code to call any method and get a property from the object. For example, I have a powershell script which gets VMs from a host using HyperV module from pshyperv.codeplex.com. (This GetVM.ps1 is just example for explanation to return objects). Once I execute the powershell script from Execute(), then it returns the objects, I want to call any method of the objects from ttt().

  1. Does it have possible solution to return objects from powershell to C#?
  2. Can you correct something wrong in my sample codes if you find(powershell,c#)?

Thank you, spark.

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; 
}

Execution Powershell Results:

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
share|improve this question

closed as not a real question by Richard, user7116, jonsca, Druid, kapa Jul 27 '12 at 12:21

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

    
"Can you correct something wrong": please tell us what is wrong: does it fail to compile? Does it give an error at runtime? Don't make use guess. –  Richard Jul 26 '12 at 16:04
    
I don't get the right return value. I want to know how to return objects from powershell to c#? I want to return the objects of 'get-vm' but c# doesn't seem to get the result. :-( –  spark Jul 26 '12 at 16:05
    
Please tell us what pipeline.Invoke's return contains? (In other words show your working so far: where in debugging this have you got stuck?) –  Richard Jul 26 '12 at 16:07
    
I got the screenshot. <iframe src="skydrive.live.com/…; width="320" height="34" frameborder="0" scrolling="no"></iframe> –  spark Jul 26 '12 at 16:22
    
another high resolution one. <iframe src="skydrive.live.com/…; width="320" height="34" frameborder="0" scrolling="no"></iframe> –  spark Jul 26 '12 at 16:23

1 Answer 1

up vote 1 down vote accepted

Looks like you've got a PSObject wrapping a string: which looks correct (given the out-string you are using). You need to extract the string from the PSObject with its BaseObject5 property.

If you are expecting a collection of the objects that Get-VM returns then don't use Out-String.

share|improve this answer
    
In the meantime, do you have any idea how to use the objects? I got the objects but can't call a method or get a property from one of objects. for example, can't get a Name from VM objects. –  spark Jul 26 '12 at 18:25
    
ret = ps.Execute(rs, "GetVM.ps1 -vmName 'ITE*'"); Collection<PSObject> results = (Collection<PSObject>)ret; foreach (PSObject obj in results) { How to call obj's any method? Debugging doesn't show any method, but properties like 'BaseObject', 'ImmediateBaseObject', etc. It's not like the result of .\GetVM.ps1 -vmName 'ITE*' |gm } –  spark Jul 26 '12 at 18:27
    
It shows 'BaseObject', 'ImmediateBaseObject', 'Members', 'Methods', 'Properties', 'TypeNames'. Is there an way to extract the methods also? –  spark Jul 26 '12 at 18:34
    
@spark You need to read up on PowerShell's "Extended Type System" (it is too much for a Stack Overflow answer). The page MSDN used to have seems to have gone but plenmty of hits on search engines. –  Richard Jul 26 '12 at 19:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.