How would I return an object or multiple values from PowerShell to executing C# code

后端 未结 3 1430
忘掉有多难
忘掉有多难 2021-01-30 17:22

Some C# code executes a powershell script with arguments. I want to get a returncode and a string back from Powershell to know, if everything was ok inside the Powershell script

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 18:02

    In your powershell script you can build an Hashtable based on your necessity:

    [hashtable]$Return = @{} 
    $Return.ReturnCode = [int]1 
    $Return.ReturnString = [string]"All Done!" 
    Return $Return 
    

    In C# code handle the Psobject in this way

     ReturnInfo ri = new ReturnInfo();
     foreach (PSObject p in psObjects)
     {
       Hashtable ht = p.ImmediateBaseObject as Hashtable;
       ri.ReturnCode = (int)ht["ReturnCode"];
       ri.ReturnText = (string)ht["ReturnString"];
     } 
    
    //Do what you want with ri object.
    

    If you want to use a PsCustomobject as in Keith Hill comment in powershell v2.0:

    powershell script:

    $return = new-object psobject -property @{ReturnCode=1;ReturnString="all done"}
    $return
    

    c# code:

    ReturnInfo ri = new ReturnInfo();
    foreach (PSObject p in psObjects)
       {
         ri.ReturnCode = (int)p.Properties["ReturnCode"].Value;
         ri.ReturnText = (string)p.Properties["ReturnString"].Value;
       }
    

提交回复
热议问题